xref: /linux/tools/net/ynl/pyynl/ynl_gen_c.py (revision 05d3030eff5b73f6fe7f86dafa3eeae004e2ede1)
1#!/usr/bin/env python3
2# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
3#
4# pylint: disable=line-too-long, missing-class-docstring, missing-function-docstring
5# pylint: disable=too-many-positional-arguments, too-many-arguments, too-many-statements
6# pylint: disable=too-many-branches, too-many-locals, too-many-instance-attributes
7# pylint: disable=too-many-nested-blocks, too-many-lines, too-few-public-methods
8# pylint: disable=broad-exception-raised, broad-exception-caught, protected-access
9
10"""
11ynl_gen_c
12
13A YNL to C code generator for both kernel and userspace protocol stubs.
14"""
15
16import argparse
17import filecmp
18import pathlib
19import os
20import re
21import shutil
22import sys
23import tempfile
24import yaml as pyyaml
25
26# pylint: disable=no-name-in-module,wrong-import-position
27sys.path.append(pathlib.Path(__file__).resolve().parent.as_posix())
28from lib import SpecFamily, SpecAttrSet, SpecAttr, SpecOperation, SpecEnumSet, SpecEnumEntry
29from lib import SpecSubMessage
30
31
32def c_upper(name):
33    return name.upper().replace('-', '_')
34
35
36def c_lower(name):
37    return name.lower().replace('-', '_')
38
39
40def limit_to_number(name):
41    """
42    Turn a string limit like u32-max or s64-min into its numerical value
43    """
44    if name[0] == 'u' and name.endswith('-min'):
45        return 0
46    width = int(name[1:-4])
47    if name[0] == 's':
48        width -= 1
49    value = (1 << width) - 1
50    if name[0] == 's' and name.endswith('-min'):
51        value = -value - 1
52    return value
53
54
55class BaseNlLib:
56    def get_family_id(self):
57        return 'ys->family_id'
58
59
60class Type(SpecAttr):
61    def __init__(self, family, attr_set, attr, value):
62        super().__init__(family, attr_set, attr, value)
63
64        self.attr = attr
65        self.attr_set = attr_set
66        self.type = attr['type']
67        self.checks = attr.get('checks', {})
68
69        self.request = False
70        self.reply = False
71
72        self.is_selector = False
73
74        if 'len' in attr:
75            self.len = attr['len']
76
77        if 'nested-attributes' in attr:
78            nested = attr['nested-attributes']
79        elif 'sub-message' in attr:
80            nested = attr['sub-message']
81        else:
82            nested = None
83
84        if nested:
85            self.nested_attrs = nested
86            if self.nested_attrs == family.name:
87                self.nested_render_name = c_lower(f"{family.ident_name}")
88            else:
89                self.nested_render_name = c_lower(f"{family.ident_name}_{self.nested_attrs}")
90
91            if self.nested_attrs in self.family.consts:
92                self.nested_struct_type = 'struct ' + self.nested_render_name + '_'
93            else:
94                self.nested_struct_type = 'struct ' + self.nested_render_name
95
96        self.c_name = c_lower(self.name)
97        if self.c_name in _C_KW:
98            self.c_name += '_'
99        if self.c_name[0].isdigit():
100            self.c_name = '_' + self.c_name
101
102        # Added by resolve():
103        self.enum_name = None
104        delattr(self, "enum_name")
105
106    def _get_real_attr(self):
107        # if the attr is for a subset return the "real" attr (just one down, does not recurse)
108        return self.family.attr_sets[self.attr_set.subset_of][self.name]
109
110    def set_request(self):
111        self.request = True
112        if self.attr_set.subset_of:
113            self._get_real_attr().set_request()
114
115    def set_reply(self):
116        self.reply = True
117        if self.attr_set.subset_of:
118            self._get_real_attr().set_reply()
119
120    def get_limit(self, limit, default=None):
121        value = self.checks.get(limit, default)
122        if value is None:
123            return value
124        if isinstance(value, int):
125            return value
126        if value in self.family.consts:
127            return self.family.consts[value]["value"]
128        return limit_to_number(value)
129
130    def get_limit_str(self, limit, default=None, suffix=''):
131        value = self.checks.get(limit, default)
132        if value is None:
133            return ''
134        if isinstance(value, int):
135            return str(value) + suffix
136        if value in self.family.consts:
137            const = self.family.consts[value]
138            if const.get('header'):
139                return c_upper(value)
140            return c_upper(f"{self.family['name']}-{value}")
141        return c_upper(value)
142
143    def resolve(self):
144        if 'parent-sub-message' in self.attr:
145            enum_name = self.attr['parent-sub-message'].enum_name
146        elif 'name-prefix' in self.attr:
147            enum_name = f"{self.attr['name-prefix']}{self.name}"
148        else:
149            enum_name = f"{self.attr_set.name_prefix}{self.name}"
150        self.enum_name = c_upper(enum_name)
151
152        if self.attr_set.subset_of:
153            if self.checks != self._get_real_attr().checks:
154                raise Exception("Overriding checks not supported by codegen, yet")
155
156    def is_multi_val(self):
157        return None
158
159    def is_scalar(self):
160        return self.type in {'u8', 'u16', 'u32', 'u64', 's32', 's64'}
161
162    def is_recursive(self):
163        return False
164
165    def is_recursive_for_op(self, ri):
166        return self.is_recursive() and not ri.op
167
168    def presence_type(self):
169        return 'present'
170
171    def presence_member(self, space, type_filter):
172        if self.presence_type() != type_filter:
173            return ''
174
175        if self.presence_type() == 'present':
176            pfx = '__' if space == 'user' else ''
177            return f"{pfx}u32 {self.c_name}:1;"
178
179        if self.presence_type() in {'len', 'count'}:
180            pfx = '__' if space == 'user' else ''
181            return f"{pfx}u32 {self.c_name};"
182        return ''
183
184    def _complex_member_type(self, _ri):
185        return None
186
187    def free_needs_iter(self):
188        return False
189
190    def _free_lines(self, _ri, var, ref):
191        if self.is_multi_val() or self.presence_type() in {'count', 'len'}:
192            return [f'free({var}->{ref}{self.c_name});']
193        return []
194
195    def free(self, ri, var, ref):
196        lines = self._free_lines(ri, var, ref)
197        for line in lines:
198            ri.cw.p(line)
199
200    # pylint: disable=assignment-from-none
201    def arg_member(self, ri):
202        member = self._complex_member_type(ri)
203        if member is not None:
204            spc = ' ' if member[-1] != '*' else ''
205            arg = [member + spc + '*' + self.c_name]
206            if self.presence_type() == 'count':
207                arg += ['unsigned int n_' + self.c_name]
208            return arg
209        raise Exception(f"Struct member not implemented for class type {self.type}")
210
211    def struct_member(self, ri):
212        member = self._complex_member_type(ri)
213        if member is not None:
214            ptr = '*' if self.is_multi_val() else ''
215            if self.is_recursive_for_op(ri):
216                ptr = '*'
217            spc = ' ' if member[-1] != '*' else ''
218            ri.cw.p(f"{member}{spc}{ptr}{self.c_name};")
219            return
220        members = self.arg_member(ri)
221        for one in members:
222            ri.cw.p(one + ';')
223
224    def _attr_policy(self, policy):
225        return '{ .type = ' + policy + ', }'
226
227    def attr_policy(self, cw):
228        policy = f'NLA_{c_upper(self.type)}'
229        if self.attr.get('byte-order') == 'big-endian':
230            if self.type in {'u16', 'u32'}:
231                policy = f'NLA_BE{self.type[1:]}'
232
233        spec = self._attr_policy(policy)
234        cw.p(f"\t[{self.enum_name}] = {spec},")
235
236    def _attr_typol(self):
237        raise Exception(f"Type policy not implemented for class type {self.type}")
238
239    def attr_typol(self, cw):
240        typol = self._attr_typol()
241        cw.p(f'[{self.enum_name}] = {"{"} .name = "{self.name}", {typol}{"}"},')
242
243    def _attr_put_line(self, ri, var, line):
244        presence = self.presence_type()
245        if presence in {'present', 'len'}:
246            ri.cw.p(f"if ({var}->_{presence}.{self.c_name})")
247        ri.cw.p(f"{line};")
248
249    def _attr_put_simple(self, ri, var, put_type):
250        line = f"ynl_attr_put_{put_type}(nlh, {self.enum_name}, {var}->{self.c_name})"
251        self._attr_put_line(ri, var, line)
252
253    def attr_put(self, ri, var):
254        raise Exception(f"Put not implemented for class type {self.type}")
255
256    def _attr_get(self, ri, var):
257        raise Exception(f"Attr get not implemented for class type {self.type}")
258
259    def attr_get(self, ri, var, first):
260        lines, init_lines, _ = self._attr_get(ri, var)
261        if isinstance(lines, str):
262            lines = [lines]
263        if isinstance(init_lines, str):
264            init_lines = [init_lines]
265
266        kw = 'if' if first else 'else if'
267        ri.cw.block_start(line=f"{kw} (type == {self.enum_name})")
268
269        if not self.is_multi_val():
270            ri.cw.p("if (ynl_attr_validate(yarg, attr))")
271            ri.cw.p("return YNL_PARSE_CB_ERROR;")
272            if self.presence_type() == 'present':
273                ri.cw.p(f"{var}->_present.{self.c_name} = 1;")
274
275        if init_lines:
276            ri.cw.nl()
277            for line in init_lines:
278                ri.cw.p(line)
279
280        for line in lines:
281            ri.cw.p(line)
282        ri.cw.block_end()
283        return True
284
285    def _setter_lines(self, ri, member, presence):
286        raise Exception(f"Setter not implemented for class type {self.type}")
287
288    def setter(self, ri, _space, direction, deref=False, ref=None, var="req"):
289        ref = (ref if ref else []) + [self.c_name]
290        member = f"{var}->{'.'.join(ref)}"
291
292        local_vars = []
293        if self.free_needs_iter():
294            local_vars += ['unsigned int i;']
295
296        code = []
297        presence = ''
298        # pylint: disable=consider-using-enumerate
299        for i in range(0, len(ref)):
300            presence = f"{var}->{'.'.join(ref[:i] + [''])}_present.{ref[i]}"
301            # Every layer below last is a nest, so we know it uses bit presence
302            # last layer is "self" and may be a complex type
303            if i == len(ref) - 1 and self.presence_type() != 'present':
304                presence = f"{var}->{'.'.join(ref[:i] + [''])}_{self.presence_type()}.{ref[i]}"
305                continue
306            code.append(presence + ' = 1;')
307        ref_path = '.'.join(ref[:-1])
308        if ref_path:
309            ref_path += '.'
310        code += self._free_lines(ri, var, ref_path)
311        code += self._setter_lines(ri, member, presence)
312
313        func_name = f"{op_prefix(ri, direction, deref=deref)}_set_{'_'.join(ref)}"
314        free = bool([x for x in code if 'free(' in x])
315        alloc = bool([x for x in code if 'alloc(' in x])
316        if free and not alloc:
317            func_name = '__' + func_name
318        ri.cw.write_func('static inline void', func_name, local_vars=local_vars,
319                         body=code,
320                         args=[f'{type_name(ri, direction, deref=deref)} *{var}'] + self.arg_member(ri))
321
322
323class TypeUnused(Type):
324    def presence_type(self):
325        return ''
326
327    def arg_member(self, ri):
328        return []
329
330    def _attr_get(self, ri, var):
331        return ['return YNL_PARSE_CB_ERROR;'], None, None
332
333    def _attr_typol(self):
334        return '.type = YNL_PT_REJECT, '
335
336    def attr_policy(self, cw):
337        pass
338
339    def attr_put(self, ri, var):
340        pass
341
342    def attr_get(self, ri, var, first):
343        pass
344
345    def setter(self, ri, space, direction, deref=False, ref=None, var=None):
346        pass
347
348
349class TypePad(Type):
350    def presence_type(self):
351        return ''
352
353    def arg_member(self, ri):
354        return []
355
356    def _attr_typol(self):
357        return '.type = YNL_PT_IGNORE, '
358
359    def attr_put(self, ri, var):
360        pass
361
362    def attr_get(self, ri, var, first):
363        pass
364
365    def attr_policy(self, cw):
366        pass
367
368    def setter(self, ri, space, direction, deref=False, ref=None, var=None):
369        pass
370
371
372class TypeScalar(Type):
373    def __init__(self, family, attr_set, attr, value):
374        super().__init__(family, attr_set, attr, value)
375
376        self.byte_order_comment = ''
377        if 'byte-order' in attr:
378            self.byte_order_comment = f" /* {attr['byte-order']} */"
379
380        # Classic families have some funny enums, don't bother
381        # computing checks, since we only need them for kernel policies
382        if not family.is_classic():
383            self._init_checks()
384
385        # Added by resolve():
386        self.is_bitfield = None
387        delattr(self, "is_bitfield")
388        self.type_name = None
389        delattr(self, "type_name")
390
391    def resolve(self):
392        self.resolve_up(super())
393
394        if 'enum-as-flags' in self.attr and self.attr['enum-as-flags']:
395            self.is_bitfield = True
396        elif 'enum' in self.attr:
397            self.is_bitfield = self.family.consts[self.attr['enum']]['type'] == 'flags'
398        else:
399            self.is_bitfield = False
400
401        if not self.is_bitfield and 'enum' in self.attr:
402            self.type_name = self.family.consts[self.attr['enum']].user_type
403        elif self.is_auto_scalar:
404            self.type_name = '__' + self.type[0] + '64'
405        else:
406            self.type_name = '__' + self.type
407
408    def _init_checks(self):
409        if 'enum' in self.attr:
410            enum = self.family.consts[self.attr['enum']]
411            low, high = enum.value_range()
412            if low is None and high is None:
413                self.checks['sparse'] = True
414            else:
415                if 'min' not in self.checks:
416                    if low != 0 or self.type[0] == 's':
417                        self.checks['min'] = low
418                if 'max' not in self.checks:
419                    self.checks['max'] = high
420
421        if 'min' in self.checks and 'max' in self.checks:
422            if self.get_limit('min') > self.get_limit('max'):
423                raise Exception(f'Invalid limit for "{self.name}" min: {self.get_limit("min")} max: {self.get_limit("max")}')
424            self.checks['range'] = True
425
426        low = min(self.get_limit('min', 0), self.get_limit('max', 0))
427        high = max(self.get_limit('min', 0), self.get_limit('max', 0))
428        if low < 0 and self.type[0] == 'u':
429            raise Exception(f'Invalid limit for "{self.name}" negative limit for unsigned type')
430        if low < -32768 or high > 32767:
431            self.checks['full-range'] = True
432
433    # pylint: disable=too-many-return-statements
434    def _attr_policy(self, policy):
435        if 'flags-mask' in self.checks or self.is_bitfield:
436            if self.is_bitfield:
437                enum = self.family.consts[self.attr['enum']]
438                mask = enum.get_mask(as_flags=True)
439            else:
440                flags = self.family.consts[self.checks['flags-mask']]
441                flag_cnt = len(flags['entries'])
442                mask = (1 << flag_cnt) - 1
443            return f"NLA_POLICY_MASK({policy}, 0x{mask:x})"
444        if 'full-range' in self.checks:
445            return f"NLA_POLICY_FULL_RANGE({policy}, &{c_lower(self.enum_name)}_range)"
446        if 'range' in self.checks:
447            return f"NLA_POLICY_RANGE({policy}, {self.get_limit_str('min')}, {self.get_limit_str('max')})"
448        if 'min' in self.checks:
449            return f"NLA_POLICY_MIN({policy}, {self.get_limit_str('min')})"
450        if 'max' in self.checks:
451            return f"NLA_POLICY_MAX({policy}, {self.get_limit_str('max')})"
452        if 'sparse' in self.checks:
453            return f"NLA_POLICY_VALIDATE_FN({policy}, &{c_lower(self.enum_name)}_validate)"
454        return super()._attr_policy(policy)
455
456    def _attr_typol(self):
457        return f'.type = YNL_PT_U{c_upper(self.type[1:])}, '
458
459    def arg_member(self, ri):
460        return [f'{self.type_name} {self.c_name}{self.byte_order_comment}']
461
462    def attr_put(self, ri, var):
463        self._attr_put_simple(ri, var, self.type)
464
465    def _attr_get(self, ri, var):
466        return f"{var}->{self.c_name} = ynl_attr_get_{self.type}(attr);", None, None
467
468    def _setter_lines(self, ri, member, presence):
469        return [f"{member} = {self.c_name};"]
470
471
472class TypeFlag(Type):
473    def arg_member(self, ri):
474        return []
475
476    def _attr_typol(self):
477        return '.type = YNL_PT_FLAG, '
478
479    def attr_put(self, ri, var):
480        self._attr_put_line(ri, var, f"ynl_attr_put(nlh, {self.enum_name}, NULL, 0)")
481
482    def _attr_get(self, ri, var):
483        return [], None, None
484
485    def _setter_lines(self, ri, member, presence):
486        return []
487
488
489class TypeString(Type):
490    def arg_member(self, ri):
491        return [f"const char *{self.c_name}"]
492
493    def presence_type(self):
494        return 'len'
495
496    def struct_member(self, ri):
497        ri.cw.p(f"char *{self.c_name};")
498
499    def _attr_typol(self):
500        typol = '.type = YNL_PT_NUL_STR, '
501        if self.is_selector:
502            typol += '.is_selector = 1, '
503        return typol
504
505    def _attr_policy(self, policy):
506        if 'exact-len' in self.checks:
507            mem = 'NLA_POLICY_EXACT_LEN(' + self.get_limit_str('exact-len') + ')'
508        else:
509            mem = '{ .type = ' + policy
510            if 'max-len' in self.checks:
511                mem += ', .len = ' + self.get_limit_str('max-len')
512            mem += ', }'
513        return mem
514
515    def attr_policy(self, cw):
516        if self.checks.get('unterminated-ok', False):
517            policy = 'NLA_STRING'
518        else:
519            policy = 'NLA_NUL_STRING'
520
521        spec = self._attr_policy(policy)
522        cw.p(f"\t[{self.enum_name}] = {spec},")
523
524    def attr_put(self, ri, var):
525        self._attr_put_simple(ri, var, 'str')
526
527    def _attr_get(self, ri, var):
528        len_mem = var + '->_len.' + self.c_name
529        return [f"{var}->{self.c_name} = malloc(len + 1);",
530                f"if (!{var}->{self.c_name})",
531                "return YNL_PARSE_CB_ERROR;",
532                f"{len_mem} = len;",
533                f"memcpy({var}->{self.c_name}, ynl_attr_get_str(attr), len);",
534                f"{var}->{self.c_name}[len] = 0;"], \
535               ['len = strnlen(ynl_attr_get_str(attr), ynl_attr_data_len(attr));'], \
536               ['unsigned int len;']
537
538    def _setter_lines(self, ri, member, presence):
539        return [f"{presence} = strlen({self.c_name});",
540                f"{member} = malloc({presence} + 1);",
541                f'memcpy({member}, {self.c_name}, {presence});',
542                f'{member}[{presence}] = 0;']
543
544
545class TypeBinary(Type):
546    def arg_member(self, ri):
547        return [f"const void *{self.c_name}", 'size_t len']
548
549    def presence_type(self):
550        return 'len'
551
552    def struct_member(self, ri):
553        ri.cw.p(f"void *{self.c_name};")
554
555    def _attr_typol(self):
556        return '.type = YNL_PT_BINARY,'
557
558    def _attr_policy(self, policy):
559        if len(self.checks) == 0:
560            pass
561        elif len(self.checks) == 1:
562            check_name = list(self.checks)[0]
563            if check_name not in {'exact-len', 'min-len', 'max-len'}:
564                raise Exception('Unsupported check for binary type: ' + check_name)
565        else:
566            raise Exception('More than one check for binary type not implemented, yet')
567
568        if len(self.checks) == 0:
569            mem = '{ .type = NLA_BINARY, }'
570        elif 'exact-len' in self.checks:
571            mem = 'NLA_POLICY_EXACT_LEN(' + self.get_limit_str('exact-len') + ')'
572        elif 'min-len' in self.checks:
573            mem = 'NLA_POLICY_MIN_LEN(' + self.get_limit_str('min-len') + ')'
574        elif 'max-len' in self.checks:
575            mem = 'NLA_POLICY_MAX_LEN(' + self.get_limit_str('max-len') + ')'
576        else:
577            raise Exception('Failed to process policy check for binary type')
578
579        return mem
580
581    def attr_put(self, ri, var):
582        self._attr_put_line(ri, var, f"ynl_attr_put(nlh, {self.enum_name}, " +
583                            f"{var}->{self.c_name}, {var}->_len.{self.c_name})")
584
585    def _attr_get(self, ri, var):
586        len_mem = var + '->_len.' + self.c_name
587        return [f"{var}->{self.c_name} = malloc(len);",
588                f"if (!{var}->{self.c_name})",
589                "return YNL_PARSE_CB_ERROR;",
590                f"{len_mem} = len;",
591                f"memcpy({var}->{self.c_name}, ynl_attr_data(attr), len);"], \
592               ['len = ynl_attr_data_len(attr);'], \
593               ['unsigned int len;']
594
595    def _setter_lines(self, ri, member, presence):
596        return [f"{presence} = len;",
597                f"{member} = malloc({presence});",
598                f'memcpy({member}, {self.c_name}, {presence});']
599
600
601class TypeBinaryStruct(TypeBinary):
602    def struct_member(self, ri):
603        ri.cw.p(f'struct {c_lower(self.get("struct"))} *{self.c_name};')
604
605    def _attr_get(self, ri, var):
606        struct_sz = 'sizeof(struct ' + c_lower(self.get("struct")) + ')'
607        len_mem = var + '->_' + self.presence_type() + '.' + self.c_name
608        return [f"if (len < {struct_sz})",
609                f"{var}->{self.c_name} = calloc(1, {struct_sz});",
610                "else",
611                f"{var}->{self.c_name} = malloc(len);",
612                f"if (!{var}->{self.c_name})",
613                "return YNL_PARSE_CB_ERROR;",
614                f"{len_mem} = len;",
615                f"memcpy({var}->{self.c_name}, ynl_attr_data(attr), len);"], \
616               ['len = ynl_attr_data_len(attr);'], \
617               ['unsigned int len;']
618
619
620class TypeBinaryScalarArray(TypeBinary):
621    def arg_member(self, ri):
622        return [f'__{self.get("sub-type")} *{self.c_name}', 'size_t count']
623
624    def presence_type(self):
625        return 'count'
626
627    def struct_member(self, ri):
628        ri.cw.p(f'__{self.get("sub-type")} *{self.c_name};')
629
630    def attr_put(self, ri, var):
631        presence = self.presence_type()
632        ri.cw.block_start(line=f"if ({var}->_{presence}.{self.c_name})")
633        ri.cw.p(f"i = {var}->_{presence}.{self.c_name} * sizeof(__{self.get('sub-type')});")
634        ri.cw.p(f"ynl_attr_put(nlh, {self.enum_name}, " +
635                f"{var}->{self.c_name}, i);")
636        ri.cw.block_end()
637
638    def _attr_get(self, ri, var):
639        len_mem = var + '->_count.' + self.c_name
640        return [f"len = (len / sizeof(__{self.get('sub-type')})) * sizeof(__{self.get('sub-type')});",
641                f"{var}->{self.c_name} = malloc(len);",
642                f"if (!{var}->{self.c_name})",
643                "return YNL_PARSE_CB_ERROR;",
644                f"{len_mem} = len / sizeof(__{self.get('sub-type')});",
645                f"memcpy({var}->{self.c_name}, ynl_attr_data(attr), len);"], \
646               ['len = ynl_attr_data_len(attr);'], \
647               ['unsigned int len;']
648
649    def _setter_lines(self, ri, member, presence):
650        return [f"{presence} = count;",
651                f"count *= sizeof(__{self.get('sub-type')});",
652                f"{member} = malloc(count);",
653                f'memcpy({member}, {self.c_name}, count);']
654
655
656class TypeBitfield32(Type):
657    def _complex_member_type(self, _ri):
658        return "struct nla_bitfield32"
659
660    def _attr_typol(self):
661        return '.type = YNL_PT_BITFIELD32, '
662
663    def _attr_policy(self, policy):
664        if 'enum' not in self.attr:
665            raise Exception('Enum required for bitfield32 attr')
666        enum = self.family.consts[self.attr['enum']]
667        mask = enum.get_mask(as_flags=True)
668        return f"NLA_POLICY_BITFIELD32({mask})"
669
670    def attr_put(self, ri, var):
671        line = f"ynl_attr_put(nlh, {self.enum_name}, &{var}->{self.c_name}, sizeof(struct nla_bitfield32))"
672        self._attr_put_line(ri, var, line)
673
674    def _attr_get(self, ri, var):
675        return f"memcpy(&{var}->{self.c_name}, ynl_attr_data(attr), sizeof(struct nla_bitfield32));", None, None
676
677    def _setter_lines(self, ri, member, presence):
678        return [f"memcpy(&{member}, {self.c_name}, sizeof(struct nla_bitfield32));"]
679
680
681class TypeNest(Type):
682    def is_recursive(self):
683        return self.family.pure_nested_structs[self.nested_attrs].recursive
684
685    def _complex_member_type(self, _ri):
686        return self.nested_struct_type
687
688    def _free_lines(self, ri, var, ref):
689        lines = []
690        at = '&'
691        if self.is_recursive_for_op(ri):
692            at = ''
693            lines += [f'if ({var}->{ref}{self.c_name})']
694        lines += [f'{self.nested_render_name}_free({at}{var}->{ref}{self.c_name});']
695        return lines
696
697    def _attr_typol(self):
698        return f'.type = YNL_PT_NEST, .nest = &{self.nested_render_name}_nest, '
699
700    def _attr_policy(self, policy):
701        return 'NLA_POLICY_NESTED(' + self.nested_render_name + '_nl_policy)'
702
703    def attr_put(self, ri, var):
704        at = '' if self.is_recursive_for_op(ri) else '&'
705        self._attr_put_line(ri, var, f"{self.nested_render_name}_put(nlh, " +
706                            f"{self.enum_name}, {at}{var}->{self.c_name})")
707
708    def _attr_get(self, ri, var):
709        pns = self.family.pure_nested_structs[self.nested_attrs]
710        args = ["&parg", "attr"]
711        for sel in pns.external_selectors():
712            args.append(f'{var}->{sel.name}')
713        get_lines = [f"if ({self.nested_render_name}_parse({', '.join(args)}))",
714                     "return YNL_PARSE_CB_ERROR;"]
715        init_lines = [f"parg.rsp_policy = &{self.nested_render_name}_nest;",
716                      f"parg.data = &{var}->{self.c_name};"]
717        return get_lines, init_lines, None
718
719    def setter(self, ri, _space, direction, deref=False, ref=None, var="req"):
720        ref = (ref if ref else []) + [self.c_name]
721
722        for _, attr in ri.family.pure_nested_structs[self.nested_attrs].member_list():
723            if attr.is_recursive():
724                continue
725            attr.setter(ri, self.nested_attrs, direction, deref=deref, ref=ref,
726                        var=var)
727
728
729class TypeMultiAttr(Type):
730    def __init__(self, family, attr_set, attr, value, base_type):
731        super().__init__(family, attr_set, attr, value)
732
733        self.base_type = base_type
734
735    def is_multi_val(self):
736        return True
737
738    def presence_type(self):
739        return 'count'
740
741    def _complex_member_type(self, ri):
742        if 'type' not in self.attr or self.attr['type'] == 'nest':
743            return self.nested_struct_type
744        if self.attr['type'] == 'binary' and 'struct' in self.attr:
745            return None  # use arg_member()
746        if self.attr['type'] == 'string':
747            return 'struct ynl_string *'
748        if self.attr['type'] in scalars:
749            scalar_pfx = '__' if ri.ku_space == 'user' else ''
750            if self.is_auto_scalar:
751                name = self.type[0] + '64'
752            else:
753                name = self.attr['type']
754            return scalar_pfx + name
755        raise Exception(f"Sub-type {self.attr['type']} not supported yet")
756
757    def arg_member(self, ri):
758        if self.type == 'binary' and 'struct' in self.attr:
759            return [f'struct {c_lower(self.attr["struct"])} *{self.c_name}',
760                    f'unsigned int n_{self.c_name}']
761        return super().arg_member(ri)
762
763    def free_needs_iter(self):
764        return self.attr['type'] in {'nest', 'string'}
765
766    def _free_lines(self, _ri, var, ref):
767        lines = []
768        if self.attr['type'] in scalars:
769            lines += [f"free({var}->{ref}{self.c_name});"]
770        elif self.attr['type'] == 'binary':
771            lines += [f"free({var}->{ref}{self.c_name});"]
772        elif self.attr['type'] == 'string':
773            lines += [
774                f"for (i = 0; i < {var}->{ref}_count.{self.c_name}; i++)",
775                f"free({var}->{ref}{self.c_name}[i]);",
776                f"free({var}->{ref}{self.c_name});",
777            ]
778        elif 'type' not in self.attr or self.attr['type'] == 'nest':
779            lines += [
780                f"for (i = 0; i < {var}->{ref}_count.{self.c_name}; i++)",
781                f'{self.nested_render_name}_free(&{var}->{ref}{self.c_name}[i]);',
782                f"free({var}->{ref}{self.c_name});",
783            ]
784        else:
785            raise Exception(f"Free of MultiAttr sub-type {self.attr['type']} not supported yet")
786        return lines
787
788    def _attr_policy(self, policy):
789        return self.base_type._attr_policy(policy)
790
791    def _attr_typol(self):
792        return self.base_type._attr_typol()
793
794    def _attr_get(self, ri, var):
795        return f'n_{self.c_name}++;', None, None
796
797    def attr_put(self, ri, var):
798        if self.attr['type'] in scalars:
799            put_type = self.type
800            ri.cw.p(f"for (i = 0; i < {var}->_count.{self.c_name}; i++)")
801            ri.cw.p(f"ynl_attr_put_{put_type}(nlh, {self.enum_name}, {var}->{self.c_name}[i]);")
802        elif self.attr['type'] == 'binary' and 'struct' in self.attr:
803            ri.cw.p(f"for (i = 0; i < {var}->_count.{self.c_name}; i++)")
804            ri.cw.p(f"ynl_attr_put(nlh, {self.enum_name}, &{var}->{self.c_name}[i], sizeof(struct {c_lower(self.attr['struct'])}));")
805        elif self.attr['type'] == 'string':
806            ri.cw.p(f"for (i = 0; i < {var}->_count.{self.c_name}; i++)")
807            ri.cw.p(f"ynl_attr_put_str(nlh, {self.enum_name}, {var}->{self.c_name}[i]->str);")
808        elif 'type' not in self.attr or self.attr['type'] == 'nest':
809            ri.cw.p(f"for (i = 0; i < {var}->_count.{self.c_name}; i++)")
810            self._attr_put_line(ri, var, f"{self.nested_render_name}_put(nlh, " +
811                                f"{self.enum_name}, &{var}->{self.c_name}[i])")
812        else:
813            raise Exception(f"Put of MultiAttr sub-type {self.attr['type']} not supported yet")
814
815    def _setter_lines(self, ri, member, presence):
816        return [f"{member} = {self.c_name};",
817                f"{presence} = n_{self.c_name};"]
818
819
820class TypeIndexedArray(Type):
821    def is_multi_val(self):
822        return True
823
824    def presence_type(self):
825        return 'count'
826
827    def _complex_member_type(self, ri):
828        if 'sub-type' not in self.attr or self.attr['sub-type'] == 'nest':
829            return self.nested_struct_type
830        if self.attr['sub-type'] in scalars:
831            scalar_pfx = '__' if ri.ku_space == 'user' else ''
832            return scalar_pfx + self.attr['sub-type']
833        if self.attr['sub-type'] == 'binary' and 'exact-len' in self.checks:
834            return None  # use arg_member()
835        raise Exception(f"Sub-type {self.attr['sub-type']} not supported yet")
836
837    def arg_member(self, ri):
838        if self.sub_type == 'binary' and 'exact-len' in self.checks:
839            return [f'unsigned char (*{self.c_name})[{self.checks["exact-len"]}]',
840                    f'unsigned int n_{self.c_name}']
841        return super().arg_member(ri)
842
843    def _attr_policy(self, policy):
844        if self.attr['sub-type'] == 'nest':
845            return f'NLA_POLICY_NESTED_ARRAY({self.nested_render_name}_nl_policy)'
846        return super()._attr_policy(policy)
847
848    def _attr_typol(self):
849        if self.attr['sub-type'] in scalars:
850            return f'.type = YNL_PT_U{c_upper(self.sub_type[1:])}, '
851        if self.attr['sub-type'] == 'binary' and 'exact-len' in self.checks:
852            return f'.type = YNL_PT_BINARY, .len = {self.checks["exact-len"]}, '
853        if self.attr['sub-type'] == 'nest':
854            return f'.type = YNL_PT_NEST, .nest = &{self.nested_render_name}_nest, '
855        raise Exception(f"Typol for IndexedArray sub-type {self.attr['sub-type']} not supported, yet")
856
857    def _attr_get(self, ri, var):
858        local_vars = ['const struct nlattr *attr2;']
859        get_lines = [f'attr_{self.c_name} = attr;',
860                     'ynl_attr_for_each_nested(attr2, attr) {',
861                     '\tif (__ynl_attr_validate(yarg, attr2, type))',
862                     '\t\treturn YNL_PARSE_CB_ERROR;',
863                     f'\tn_{self.c_name}++;',
864                     '}']
865        return get_lines, None, local_vars
866
867    def attr_put(self, ri, var):
868        ri.cw.p(f'array = ynl_attr_nest_start(nlh, {self.enum_name});')
869        if self.sub_type in scalars:
870            put_type = self.sub_type
871            ri.cw.block_start(line=f'for (i = 0; i < {var}->_count.{self.c_name}; i++)')
872            ri.cw.p(f"ynl_attr_put_{put_type}(nlh, i, {var}->{self.c_name}[i]);")
873            ri.cw.block_end()
874        elif self.sub_type == 'binary' and 'exact-len' in self.checks:
875            ri.cw.p(f'for (i = 0; i < {var}->_count.{self.c_name}; i++)')
876            ri.cw.p(f"ynl_attr_put(nlh, i, {var}->{self.c_name}[i], {self.checks['exact-len']});")
877        elif self.sub_type == 'nest':
878            ri.cw.p(f'for (i = 0; i < {var}->_count.{self.c_name}; i++)')
879            ri.cw.p(f"{self.nested_render_name}_put(nlh, i, &{var}->{self.c_name}[i]);")
880        else:
881            raise Exception(f"Put for IndexedArray sub-type {self.attr['sub-type']} not supported, yet")
882        ri.cw.p('ynl_attr_nest_end(nlh, array);')
883
884    def _setter_lines(self, ri, member, presence):
885        return [f"{member} = {self.c_name};",
886                f"{presence} = n_{self.c_name};"]
887
888    def free_needs_iter(self):
889        return self.sub_type == 'nest'
890
891    def _free_lines(self, _ri, var, ref):
892        lines = []
893        if self.sub_type == 'nest':
894            lines += [
895                f"for (i = 0; i < {var}->{ref}_count.{self.c_name}; i++)",
896                f'{self.nested_render_name}_free(&{var}->{ref}{self.c_name}[i]);',
897            ]
898        lines += (f"free({var}->{ref}{self.c_name});",)
899        return lines
900
901class TypeNestTypeValue(Type):
902    def _complex_member_type(self, _ri):
903        return self.nested_struct_type
904
905    def _attr_typol(self):
906        return f'.type = YNL_PT_NEST, .nest = &{self.nested_render_name}_nest, '
907
908    def _attr_get(self, ri, var):
909        prev = 'attr'
910        tv_args = ''
911        get_lines = []
912        local_vars = []
913        init_lines = [f"parg.rsp_policy = &{self.nested_render_name}_nest;",
914                      f"parg.data = &{var}->{self.c_name};"]
915        if 'type-value' in self.attr:
916            tv_names = [c_lower(x) for x in self.attr["type-value"]]
917            local_vars += [f'const struct nlattr *attr_{", *attr_".join(tv_names)};']
918            local_vars += [f'__u32 {", ".join(tv_names)};']
919            for level in self.attr["type-value"]:
920                level = c_lower(level)
921                get_lines += [f'attr_{level} = ynl_attr_data({prev});']
922                get_lines += [f'{level} = ynl_attr_type(attr_{level});']
923                prev = 'attr_' + level
924
925            tv_args = f", {', '.join(tv_names)}"
926
927        get_lines += [f"{self.nested_render_name}_parse(&parg, {prev}{tv_args});"]
928        return get_lines, init_lines, local_vars
929
930
931class TypeSubMessage(TypeNest):
932    def __init__(self, family, attr_set, attr, value):
933        super().__init__(family, attr_set, attr, value)
934
935        self.selector = Selector(attr, attr_set)
936
937    def _attr_typol(self):
938        typol = f'.type = YNL_PT_NEST, .nest = &{self.nested_render_name}_nest, '
939        typol += '.is_submsg = 1, '
940        # Reverse-parsing of the policy (ynl_err_walk() in ynl.c) does not
941        # support external selectors. No family uses sub-messages with external
942        # selector for requests so this is fine for now.
943        if not self.selector.is_external():
944            typol += f'.selector_type = {self.attr_set[self["selector"]].value} '
945        return typol
946
947    def _attr_get(self, ri, var):
948        selector = self['selector']
949        sel = c_lower(selector)
950        if self.selector.is_external():
951            sel_var = f"_sel_{sel}"
952        else:
953            sel_var = f"{var}->{sel}"
954
955        local_vars = None
956
957        if self.selector.is_enum_val() and not self.selector.is_external():
958            enum = self.family.consts[self.selector.get_enum_name()]
959            pres_var = f"{var}->_present.{sel}"
960            parse_sel = f"{sel}_str"
961            local_vars = [f'const char *{parse_sel};']
962
963            get_lines = [
964                f'if (!{pres_var})',
965                f'return ynl_submsg_failed(yarg, "{self.name}", "{selector}");',
966                f'{parse_sel} = {enum.render_name}_str({sel_var});',
967                f'if (!{parse_sel})',
968                f'return ynl_submsg_failed(yarg, "{self.name}", "enum-lookup-failed");']
969        else:
970            parse_sel = sel_var
971            get_lines = [f'if (!{parse_sel})',
972                         f'return ynl_submsg_failed(yarg, "{self.name}", "{selector}");']
973
974        get_lines += [f"if ({self.nested_render_name}_parse(&parg, {parse_sel}, attr))",
975                      "return YNL_PARSE_CB_ERROR;"]
976        init_lines = [f"parg.rsp_policy = &{self.nested_render_name}_nest;",
977                      f"parg.data = &{var}->{self.c_name};"]
978        return get_lines, init_lines, local_vars
979
980
981class Selector:
982    def __init__(self, msg_attr, attr_set):
983        self.name = msg_attr["selector"]
984
985        if self.name in attr_set:
986            self.attr = attr_set[self.name]
987            self.attr.is_selector = True
988            self._external = False
989        else:
990            # The selector will need to get passed down thru the structs
991            self.attr = None
992            self._external = True
993
994    def set_attr(self, attr):
995        self.attr = attr
996
997    def is_external(self):
998        return self._external
999
1000    def is_enum_val(self):
1001        return self.get_enum_name() is not None
1002
1003    def get_enum_name(self):
1004        return self.attr and self.attr.attr.get("enum")
1005
1006
1007class Struct:
1008    def __init__(self, family, space_name, type_list=None, fixed_header=None,
1009                 inherited=None, submsg=None):
1010        self.family = family
1011        self.space_name = space_name
1012        self.attr_set = family.attr_sets[space_name]
1013        # Stored by reference, _load_nested_set_nest() fills the list in
1014        # after constructing us.
1015        self._inherited = inherited if inherited is not None else []
1016        self.inherited = []
1017        self.fixed_header = None
1018        if fixed_header:
1019            self.fixed_header = 'struct ' + c_lower(fixed_header)
1020        self.submsg = submsg
1021
1022        self.nested = type_list is None
1023        if family.name == c_lower(space_name):
1024            self.render_name = c_lower(family.ident_name)
1025        else:
1026            self.render_name = c_lower(family.ident_name + '-' + space_name)
1027        self.struct_name = 'struct ' + self.render_name
1028        if self.nested and space_name in family.consts:
1029            self.struct_name += '_'
1030        self.ptr_name = self.struct_name + ' *'
1031        # All attr sets this one contains, directly or multiple levels down
1032        self.child_nests = set()
1033
1034        self.request = False
1035        self.reply = False
1036        self.recursive = False
1037        self.in_multi_val = False  # used by a MultiAttr or and legacy arrays
1038
1039        self.attr_list = []
1040        self.attrs = {}
1041        if type_list is not None:
1042            for t in type_list:
1043                self.attr_list.append((t, self.attr_set[t]),)
1044        else:
1045            for t in self.attr_set:
1046                self.attr_list.append((t, self.attr_set[t]),)
1047
1048        max_val = 0
1049        self.attr_max_val = None
1050        for name, attr in self.attr_list:
1051            if attr.value >= max_val:
1052                max_val = attr.value
1053                self.attr_max_val = attr
1054            self.attrs[name] = attr
1055
1056    def __iter__(self):
1057        yield from self.attrs
1058
1059    def __getitem__(self, key):
1060        return self.attrs[key]
1061
1062    def member_list(self):
1063        return self.attr_list
1064
1065    def set_inherited(self, new_inherited):
1066        if self.submsg:
1067            raise Exception("Nesting a sub-message as an attribute set not supported")
1068        if self._inherited != new_inherited:
1069            raise Exception("Inheriting different members, or a different order, not supported")
1070        self.inherited = [c_lower(x) for x in self._inherited]
1071
1072    def external_selectors(self):
1073        sels = []
1074        for _name, attr in self.attr_list:
1075            if isinstance(attr, TypeSubMessage) and attr.selector.is_external():
1076                sels.append(attr.selector)
1077        return sels
1078
1079    def free_needs_iter(self):
1080        for _, attr in self.attr_list:
1081            if attr.free_needs_iter():
1082                return True
1083        return False
1084
1085
1086class EnumEntry(SpecEnumEntry):
1087    def __init__(self, enum_set, yaml, prev, value_start):
1088        super().__init__(enum_set, yaml, prev, value_start)
1089
1090        if prev:
1091            self.value_change = self.value != prev.value + 1
1092        else:
1093            self.value_change = self.value != 0
1094        self.value_change = self.value_change or self.enum_set['type'] == 'flags'
1095
1096        # Added by resolve:
1097        self.c_name = None
1098        delattr(self, "c_name")
1099
1100    def resolve(self):
1101        self.resolve_up(super())
1102
1103        self.c_name = c_upper(self.enum_set.value_pfx + self.name)
1104
1105
1106class EnumSet(SpecEnumSet):
1107    def __init__(self, family, yaml):
1108        self.render_name = c_lower(family.ident_name + '-' + yaml['name'])
1109
1110        if 'enum-name' in yaml:
1111            if yaml['enum-name']:
1112                self.enum_name = 'enum ' + c_lower(yaml['enum-name'])
1113                self.user_type = self.enum_name
1114            else:
1115                self.enum_name = None
1116        else:
1117            self.enum_name = 'enum ' + self.render_name
1118
1119        if self.enum_name:
1120            self.user_type = self.enum_name
1121        else:
1122            self.user_type = 'int'
1123
1124        self.value_pfx = yaml.get('name-prefix', f"{family.ident_name}-{yaml['name']}-")
1125        self.header = yaml.get('header', None)
1126        self.enum_cnt_name = yaml.get('enum-cnt-name', None)
1127
1128        super().__init__(family, yaml)
1129
1130    def new_entry(self, entry, prev_entry, value_start):
1131        return EnumEntry(self, entry, prev_entry, value_start)
1132
1133    def value_range(self):
1134        low = min(x.value for x in self.entries.values())
1135        high = max(x.value for x in self.entries.values())
1136
1137        if high - low + 1 != len(self.entries):
1138            return None, None
1139
1140        return low, high
1141
1142
1143class AttrSet(SpecAttrSet):
1144    def __init__(self, family, yaml):
1145        super().__init__(family, yaml)
1146
1147        if self.subset_of is None:
1148            if 'name-prefix' in yaml:
1149                pfx = yaml['name-prefix']
1150            elif self.name == family.name:
1151                pfx = family.ident_name + '-a-'
1152            else:
1153                pfx = f"{family.ident_name}-a-{self.name}-"
1154            self.name_prefix = c_upper(pfx)
1155            self.max_name = c_upper(self.yaml.get('attr-max-name', f"{self.name_prefix}max"))
1156            self.cnt_name = c_upper(self.yaml.get('attr-cnt-name', f"__{self.name_prefix}max"))
1157        else:
1158            self.name_prefix = family.attr_sets[self.subset_of].name_prefix
1159            self.max_name = family.attr_sets[self.subset_of].max_name
1160            self.cnt_name = family.attr_sets[self.subset_of].cnt_name
1161
1162        # Added by resolve:
1163        self.c_name = None
1164        delattr(self, "c_name")
1165
1166    def resolve(self):
1167        self.c_name = c_lower(self.name)
1168        if self.c_name in _C_KW:
1169            self.c_name += '_'
1170        if self.c_name == self.family.c_name:
1171            self.c_name = ''
1172
1173    def new_attr(self, elem, value):
1174        if elem['type'] in scalars:
1175            t = TypeScalar(self.family, self, elem, value)
1176        elif elem['type'] == 'unused':
1177            t = TypeUnused(self.family, self, elem, value)
1178        elif elem['type'] == 'pad':
1179            t = TypePad(self.family, self, elem, value)
1180        elif elem['type'] == 'flag':
1181            t = TypeFlag(self.family, self, elem, value)
1182        elif elem['type'] == 'string':
1183            t = TypeString(self.family, self, elem, value)
1184        elif elem['type'] == 'binary':
1185            if 'struct' in elem:
1186                t = TypeBinaryStruct(self.family, self, elem, value)
1187            elif elem.get('sub-type') in scalars:
1188                t = TypeBinaryScalarArray(self.family, self, elem, value)
1189            else:
1190                t = TypeBinary(self.family, self, elem, value)
1191        elif elem['type'] == 'bitfield32':
1192            t = TypeBitfield32(self.family, self, elem, value)
1193        elif elem['type'] == 'nest':
1194            t = TypeNest(self.family, self, elem, value)
1195        elif elem['type'] == 'indexed-array' and 'sub-type' in elem:
1196            if elem["sub-type"] in ['binary', 'nest', 'u32']:
1197                t = TypeIndexedArray(self.family, self, elem, value)
1198            else:
1199                raise Exception(f'new_attr: unsupported sub-type {elem["sub-type"]}')
1200        elif elem['type'] == 'nest-type-value':
1201            t = TypeNestTypeValue(self.family, self, elem, value)
1202        elif elem['type'] == 'sub-message':
1203            t = TypeSubMessage(self.family, self, elem, value)
1204        else:
1205            raise Exception(f"No typed class for type {elem['type']}")
1206
1207        if 'multi-attr' in elem and elem['multi-attr']:
1208            t = TypeMultiAttr(self.family, self, elem, value, t)
1209
1210        return t
1211
1212
1213class Operation(SpecOperation):
1214    def __init__(self, family, yaml, req_value, rsp_value):
1215        # Fill in missing operation properties (for fixed hdr-only msgs)
1216        for mode in ['do', 'dump', 'event']:
1217            for direction in ['request', 'reply']:
1218                try:
1219                    yaml[mode][direction].setdefault('attributes', [])
1220                except KeyError:
1221                    pass
1222
1223        super().__init__(family, yaml, req_value, rsp_value)
1224
1225        self.render_name = c_lower(family.ident_name + '_' + self.name)
1226
1227        self.dual_policy = ('do' in yaml and 'request' in yaml['do']) and \
1228                         ('dump' in yaml and 'request' in yaml['dump'])
1229
1230        self.has_ntf = False
1231
1232        # Added by resolve:
1233        self.enum_name = None
1234        delattr(self, "enum_name")
1235
1236    def resolve(self):
1237        self.resolve_up(super())
1238
1239        if not self.is_async:
1240            self.enum_name = self.family.op_prefix + c_upper(self.name)
1241        else:
1242            self.enum_name = self.family.async_op_prefix + c_upper(self.name)
1243
1244    def mark_has_ntf(self):
1245        self.has_ntf = True
1246
1247
1248class SubMessage(SpecSubMessage):
1249    def __init__(self, family, yaml):
1250        super().__init__(family, yaml)
1251
1252        self.render_name = c_lower(family.ident_name + '-' + yaml['name'])
1253
1254    def resolve(self):
1255        self.resolve_up(super())
1256
1257
1258class Family(SpecFamily):
1259    def __init__(self, file_name, exclude_ops, fn_prefix):
1260        # Added by resolve:
1261        self.c_name = None
1262        delattr(self, "c_name")
1263        self.op_prefix = None
1264        delattr(self, "op_prefix")
1265        self.async_op_prefix = None
1266        delattr(self, "async_op_prefix")
1267        self.mcgrps = None
1268        delattr(self, "mcgrps")
1269        self.consts = None
1270        delattr(self, "consts")
1271        self.hooks = None
1272        delattr(self, "hooks")
1273
1274        self.root_sets = {}
1275        self.pure_nested_structs = {}
1276        self.kernel_policy = None
1277        self.global_policy = None
1278        self.global_policy_set = None
1279
1280        super().__init__(file_name, exclude_ops=exclude_ops)
1281
1282        self.fam_key = c_upper(self.yaml.get('c-family-name', self.yaml["name"] + '_FAMILY_NAME'))
1283        self.ver_key = c_upper(self.yaml.get('c-version-name', self.yaml["name"] + '_FAMILY_VERSION'))
1284
1285        if 'definitions' not in self.yaml:
1286            self.yaml['definitions'] = []
1287
1288        if 'uapi-header' in self.yaml:
1289            self.uapi_header = self.yaml['uapi-header']
1290        else:
1291            self.uapi_header = f"linux/{self.ident_name}.h"
1292        if self.uapi_header.startswith("linux/") and self.uapi_header.endswith('.h'):
1293            self.uapi_header_name = self.uapi_header[6:-2]
1294        else:
1295            self.uapi_header_name = self.ident_name
1296
1297        self.fn_prefix = fn_prefix if fn_prefix else f'{self.ident_name}-nl'
1298
1299    def resolve(self):
1300        self.resolve_up(super())
1301
1302        self.c_name = c_lower(self.ident_name)
1303        if 'name-prefix' in self.yaml['operations']:
1304            self.op_prefix = c_upper(self.yaml['operations']['name-prefix'])
1305        else:
1306            self.op_prefix = c_upper(self.yaml['name'] + '-cmd-')
1307        if 'async-prefix' in self.yaml['operations']:
1308            self.async_op_prefix = c_upper(self.yaml['operations']['async-prefix'])
1309        else:
1310            self.async_op_prefix = self.op_prefix
1311
1312        self.mcgrps = self.yaml.get('mcast-groups', {'list': []})
1313
1314        self.hooks = {}
1315        for when in ['pre', 'post']:
1316            self.hooks[when] = {}
1317            for op_mode in ['do', 'dump']:
1318                self.hooks[when][op_mode] = {}
1319                self.hooks[when][op_mode]['set'] = set()
1320                self.hooks[when][op_mode]['list'] = []
1321
1322        # dict space-name -> 'request': set(attrs), 'reply': set(attrs)
1323        self.root_sets = {}
1324        # dict space-name -> Struct
1325        self.pure_nested_structs = {}
1326
1327        self._mark_notify()
1328        self._mock_up_events()
1329
1330        self._load_root_sets()
1331        self._load_nested_sets()
1332        self._load_attr_use()
1333        self._load_selector_passing()
1334        self._load_hooks()
1335
1336        self.kernel_policy = self.yaml.get('kernel-policy', 'split')
1337        if self.kernel_policy == 'global':
1338            self._load_global_policy()
1339
1340    def new_enum(self, elem):
1341        return EnumSet(self, elem)
1342
1343    def new_attr_set(self, elem):
1344        return AttrSet(self, elem)
1345
1346    def new_operation(self, elem, req_value, rsp_value):
1347        return Operation(self, elem, req_value, rsp_value)
1348
1349    def new_sub_message(self, elem):
1350        return SubMessage(self, elem)
1351
1352    def is_classic(self):
1353        return self.proto == 'netlink-raw'
1354
1355    def _mark_notify(self):
1356        for op in self.msgs.values():
1357            if 'notify' in op:
1358                self.ops[op['notify']].mark_has_ntf()
1359
1360    # Fake a 'do' equivalent of all events, so that we can render their response parsing
1361    def _mock_up_events(self):
1362        for op in self.yaml['operations']['list']:
1363            if 'event' in op:
1364                op['do'] = {
1365                    'reply': {
1366                        'attributes': op['event']['attributes']
1367                    }
1368                }
1369
1370    def _load_root_sets(self):
1371        for _op_name, op in self.msgs.items():
1372            if 'attribute-set' not in op:
1373                continue
1374
1375            req_attrs = set()
1376            rsp_attrs = set()
1377            for op_mode in ['do', 'dump']:
1378                if op_mode in op and 'request' in op[op_mode]:
1379                    req_attrs.update(set(op[op_mode]['request']['attributes']))
1380                if op_mode in op and 'reply' in op[op_mode]:
1381                    rsp_attrs.update(set(op[op_mode]['reply']['attributes']))
1382            if 'event' in op:
1383                rsp_attrs.update(set(op['event']['attributes']))
1384
1385            if op['attribute-set'] not in self.root_sets:
1386                self.root_sets[op['attribute-set']] = {'request': req_attrs, 'reply': rsp_attrs}
1387            else:
1388                self.root_sets[op['attribute-set']]['request'].update(req_attrs)
1389                self.root_sets[op['attribute-set']]['reply'].update(rsp_attrs)
1390
1391    def _sort_pure_types(self):
1392        # Try to reorder according to dependencies
1393        pns_key_list = list(self.pure_nested_structs.keys())
1394        pns_key_seen = set()
1395        rounds = len(pns_key_list) ** 2  # it's basically bubble sort
1396        for _ in range(rounds):
1397            if len(pns_key_list) == 0:
1398                break
1399            name = pns_key_list.pop(0)
1400            finished = True
1401            for _, spec in self.attr_sets[name].items():
1402                if 'nested-attributes' in spec:
1403                    nested = spec['nested-attributes']
1404                elif 'sub-message' in spec:
1405                    nested = spec.sub_message
1406                else:
1407                    continue
1408
1409                # If the unknown nest we hit is recursive it's fine, it'll be a pointer
1410                if self.pure_nested_structs[nested].recursive:
1411                    continue
1412                if nested not in pns_key_seen:
1413                    # Dicts are sorted, this will make struct last
1414                    struct = self.pure_nested_structs.pop(name)
1415                    self.pure_nested_structs[name] = struct
1416                    finished = False
1417                    break
1418            if finished:
1419                pns_key_seen.add(name)
1420            else:
1421                pns_key_list.append(name)
1422
1423    def _load_nested_set_nest(self, spec):
1424        inherit = []
1425        nested = spec['nested-attributes']
1426        if nested not in self.root_sets:
1427            if nested not in self.pure_nested_structs:
1428                self.pure_nested_structs[nested] = \
1429                    Struct(self, nested, inherited=inherit,
1430                           fixed_header=spec.get('fixed-header'))
1431        else:
1432            raise Exception(f'Using attr set as root and nested not supported - {nested}')
1433
1434        if 'type-value' in spec:
1435            if nested in self.root_sets:
1436                raise Exception("Inheriting members to a space used as root not supported")
1437            inherit.extend(spec['type-value'])
1438        elif spec['type'] == 'indexed-array':
1439            inherit.append('idx')
1440        self.pure_nested_structs[nested].set_inherited(inherit)
1441
1442        return nested
1443
1444    def _load_nested_set_submsg(self, spec):
1445        # Fake the struct type for the sub-message itself
1446        # its not a attr_set but codegen wants attr_sets.
1447        submsg = self.sub_msgs[spec["sub-message"]]
1448        nested = submsg.name
1449
1450        attrs = []
1451        for name, fmt in submsg.formats.items():
1452            attr = {
1453                "name": name,
1454                "parent-sub-message": spec,
1455            }
1456            if 'attribute-set' in fmt:
1457                attr |= {
1458                    "type": "nest",
1459                    "nested-attributes": fmt['attribute-set'],
1460                }
1461                if 'fixed-header' in fmt:
1462                    attr |= { "fixed-header": fmt["fixed-header"] }
1463            elif 'fixed-header' in fmt:
1464                attr |= {
1465                    "type": "binary",
1466                    "struct": fmt["fixed-header"],
1467                }
1468            else:
1469                attr["type"] = "flag"
1470            attrs.append(attr)
1471
1472        self.attr_sets[nested] = AttrSet(self, {
1473            "name": nested,
1474            "name-pfx": self.name + '-' + spec.name + '-',
1475            "attributes": attrs
1476        })
1477
1478        if nested not in self.pure_nested_structs:
1479            self.pure_nested_structs[nested] = Struct(self, nested, submsg=submsg)
1480
1481        return nested
1482
1483    def _load_nested_sets(self):
1484        attr_set_queue = list(self.root_sets.keys())
1485        attr_set_seen = set(self.root_sets.keys())
1486
1487        while attr_set_queue:
1488            a_set = attr_set_queue.pop(0)
1489            for attr, spec in self.attr_sets[a_set].items():
1490                if 'nested-attributes' in spec:
1491                    nested = self._load_nested_set_nest(spec)
1492                elif 'sub-message' in spec:
1493                    nested = self._load_nested_set_submsg(spec)
1494                else:
1495                    continue
1496
1497                if nested not in attr_set_seen:
1498                    attr_set_queue.append(nested)
1499                    attr_set_seen.add(nested)
1500
1501        for root_set, rs_members in self.root_sets.items():
1502            for attr, spec in self.attr_sets[root_set].items():
1503                if 'nested-attributes' in spec:
1504                    nested = spec['nested-attributes']
1505                elif 'sub-message' in spec:
1506                    nested = spec.sub_message
1507                else:
1508                    nested = None
1509
1510                if nested:
1511                    if attr in rs_members['request']:
1512                        self.pure_nested_structs[nested].request = True
1513                    if attr in rs_members['reply']:
1514                        self.pure_nested_structs[nested].reply = True
1515
1516                    if spec.is_multi_val():
1517                        child = self.pure_nested_structs.get(nested)
1518                        child.in_multi_val = True
1519
1520        self._sort_pure_types()
1521
1522        # Propagate the request / reply / recursive
1523        for attr_set, struct in reversed(self.pure_nested_structs.items()):
1524            for _, spec in self.attr_sets[attr_set].items():
1525                if attr_set in struct.child_nests:
1526                    struct.recursive = True
1527
1528                if 'nested-attributes' in spec:
1529                    child_name = spec['nested-attributes']
1530                elif 'sub-message' in spec:
1531                    child_name = spec.sub_message
1532                else:
1533                    continue
1534
1535                struct.child_nests.add(child_name)
1536                child = self.pure_nested_structs.get(child_name)
1537                if child:
1538                    if not child.recursive:
1539                        struct.child_nests.update(child.child_nests)
1540                    child.request |= struct.request
1541                    child.reply |= struct.reply
1542                    if spec.is_multi_val():
1543                        child.in_multi_val = True
1544
1545        self._sort_pure_types()
1546
1547    def _load_attr_use(self):
1548        for _, struct in self.pure_nested_structs.items():
1549            if struct.request:
1550                for _, arg in struct.member_list():
1551                    arg.set_request()
1552            if struct.reply:
1553                for _, arg in struct.member_list():
1554                    arg.set_reply()
1555
1556        for root_set, rs_members in self.root_sets.items():
1557            for attr, spec in self.attr_sets[root_set].items():
1558                if attr in rs_members['request']:
1559                    spec.set_request()
1560                if attr in rs_members['reply']:
1561                    spec.set_reply()
1562
1563    def _load_selector_passing(self):
1564        def all_structs():
1565            for k, v in reversed(self.pure_nested_structs.items()):
1566                yield k, v
1567            for k, _ in self.root_sets.items():
1568                yield k, None  # we don't have a struct, but it must be terminal
1569
1570        for attr_set, _struct in all_structs():
1571            for _, spec in self.attr_sets[attr_set].items():
1572                if 'nested-attributes' in spec:
1573                    child_name = spec['nested-attributes']
1574                elif 'sub-message' in spec:
1575                    child_name = spec.sub_message
1576                else:
1577                    continue
1578
1579                child = self.pure_nested_structs.get(child_name)
1580                for selector in child.external_selectors():
1581                    if selector.name in self.attr_sets[attr_set]:
1582                        sel_attr = self.attr_sets[attr_set][selector.name]
1583                        selector.set_attr(sel_attr)
1584                    else:
1585                        raise Exception("Passing selector thru more than one layer not supported")
1586
1587    def _load_global_policy(self):
1588        global_set = set()
1589        attr_set_name = None
1590        for _op_name, op in self.ops.items():
1591            if not op:
1592                continue
1593            if 'attribute-set' not in op:
1594                continue
1595
1596            if attr_set_name is None:
1597                attr_set_name = op['attribute-set']
1598            if attr_set_name != op['attribute-set']:
1599                raise Exception('For a global policy all ops must use the same set')
1600
1601            for op_mode in ['do', 'dump']:
1602                if op_mode in op:
1603                    req = op[op_mode].get('request')
1604                    if req:
1605                        global_set.update(req.get('attributes', []))
1606
1607        self.global_policy = []
1608        self.global_policy_set = attr_set_name
1609        for attr in self.attr_sets[attr_set_name]:
1610            if attr in global_set:
1611                self.global_policy.append(attr)
1612
1613    def _load_hooks(self):
1614        for op in self.ops.values():
1615            for op_mode in ['do', 'dump']:
1616                if op_mode not in op:
1617                    continue
1618                for when in ['pre', 'post']:
1619                    if when not in op[op_mode]:
1620                        continue
1621                    name = op[op_mode][when]
1622                    if name in self.hooks[when][op_mode]['set']:
1623                        continue
1624                    self.hooks[when][op_mode]['set'].add(name)
1625                    self.hooks[when][op_mode]['list'].append(name)
1626
1627
1628class RenderInfo:
1629    def __init__(self, cw, family, ku_space, op, op_mode, attr_set=None):
1630        self.family = family
1631        self.nl = cw.nlib
1632        self.ku_space = ku_space
1633        self.op_mode = op_mode
1634        self.op = op
1635
1636        fixed_hdr = op.fixed_header if op else None
1637        self.fixed_hdr_len = 'ys->family->hdr_len'
1638        if op and op.fixed_header:
1639            if op.fixed_header != family.fixed_header:
1640                if family.is_classic():
1641                    self.fixed_hdr_len = f"sizeof(struct {c_lower(fixed_hdr)})"
1642                else:
1643                    raise Exception("Per-op fixed header not supported, yet")
1644
1645
1646        # 'do' and 'dump' response parsing is identical
1647        self.type_consistent = True
1648        self.type_oneside = False
1649        if op_mode != 'do' and 'dump' in op:
1650            if 'do' in op:
1651                if ('reply' in op['do']) != ('reply' in op["dump"]):
1652                    self.type_consistent = False
1653                elif 'reply' in op['do'] and op["do"]["reply"] != op["dump"]["reply"]:
1654                    self.type_consistent = False
1655            else:
1656                self.type_consistent = True
1657                self.type_oneside = True
1658
1659        self.attr_set = attr_set
1660        if not self.attr_set:
1661            self.attr_set = op['attribute-set']
1662
1663        self.type_name_conflict = False
1664        if op:
1665            self.type_name = c_lower(op.name)
1666        else:
1667            self.type_name = c_lower(attr_set)
1668            if attr_set in family.consts:
1669                self.type_name_conflict = True
1670
1671        self.cw = cw
1672
1673        self.struct = {}
1674        if op_mode == 'notify':
1675            op_mode = 'do' if 'do' in op else 'dump'
1676        for op_dir in ['request', 'reply']:
1677            if op:
1678                type_list = []
1679                if op_dir in op[op_mode]:
1680                    type_list = op[op_mode][op_dir]['attributes']
1681                self.struct[op_dir] = Struct(family, self.attr_set,
1682                                             fixed_header=fixed_hdr,
1683                                             type_list=type_list)
1684        if op_mode == 'event':
1685            self.struct['reply'] = Struct(family, self.attr_set,
1686                                          fixed_header=fixed_hdr,
1687                                          type_list=op['event']['attributes'])
1688
1689    def type_empty(self, key):
1690        return len(self.struct[key].attr_list) == 0 and \
1691            self.struct['request'].fixed_header is None
1692
1693    def needs_nlflags(self, direction):
1694        return self.op_mode == 'do' and direction == 'request' and self.family.is_classic()
1695
1696
1697class CodeWriter:
1698    def __init__(self, nlib, out_file=None, overwrite=True):
1699        self.nlib = nlib
1700        self._overwrite = overwrite
1701
1702        self._nl = False
1703        self._block_end = False
1704        self._silent_block = False
1705        self._ind = 0
1706        self._ifdef_block = None
1707        if out_file is None:
1708            self._out = os.sys.stdout
1709        else:
1710            # pylint: disable=consider-using-with
1711            self._out = tempfile.NamedTemporaryFile('w+')
1712            self._out_file = out_file
1713
1714    def __del__(self):
1715        self.close_out_file()
1716
1717    def close_out_file(self):
1718        if self._out == os.sys.stdout:
1719            return
1720        # Avoid modifying the file if contents didn't change
1721        self._out.flush()
1722        if not self._overwrite and os.path.isfile(self._out_file):
1723            if filecmp.cmp(self._out.name, self._out_file, shallow=False):
1724                return
1725        with open(self._out_file, 'w+', encoding='utf-8') as out_file:
1726            self._out.seek(0)
1727            shutil.copyfileobj(self._out, out_file)
1728            self._out.close()
1729        self._out = os.sys.stdout
1730
1731    @classmethod
1732    def _is_cond(cls, line):
1733        return line.startswith('if') or line.startswith('while') or line.startswith('for')
1734
1735    def p(self, line, add_ind=0):
1736        if self._block_end:
1737            self._block_end = False
1738            if line.startswith('else'):
1739                line = '} ' + line
1740            else:
1741                self._out.write('\t' * self._ind + '}\n')
1742
1743        if self._nl:
1744            self._out.write('\n')
1745            self._nl = False
1746
1747        ind = self._ind
1748        if line[-1] == ':':
1749            ind -= 1
1750        if self._silent_block:
1751            ind += 1
1752        self._silent_block = line.endswith(')') and CodeWriter._is_cond(line)
1753        self._silent_block |= line.strip() == 'else'
1754        if line[0] == '#':
1755            ind = 0
1756        if add_ind:
1757            ind += add_ind
1758        self._out.write('\t' * ind + line + '\n')
1759
1760    def nl(self):
1761        self._nl = True
1762
1763    def block_start(self, line=''):
1764        if line:
1765            line = line + ' '
1766        self.p(line + '{')
1767        self._ind += 1
1768
1769    def block_end(self, line=''):
1770        if line and line[0] not in {';', ','}:
1771            line = ' ' + line
1772        self._ind -= 1
1773        self._nl = False
1774        if not line:
1775            # Delay printing closing bracket in case "else" comes next
1776            if self._block_end:
1777                self._out.write('\t' * (self._ind + 1) + '}\n')
1778            self._block_end = True
1779        else:
1780            self.p('}' + line)
1781
1782    def write_doc_line(self, doc, indent=True):
1783        words = doc.split()
1784        line = ' *'
1785        for word in words:
1786            if len(line) + len(word) >= 79:
1787                self.p(line)
1788                line = ' *'
1789                if indent:
1790                    line += '  '
1791            line += ' ' + word
1792        self.p(line)
1793
1794    def write_func_prot(self, qual_ret, name, args=None, doc=None, suffix=''):
1795        if not args:
1796            args = ['void']
1797
1798        if doc:
1799            self.p('/*')
1800            self.p(' * ' + doc)
1801            self.p(' */')
1802
1803        oneline = qual_ret
1804        if qual_ret[-1] != '*':
1805            oneline += ' '
1806        oneline += f"{name}({', '.join(args)}){suffix}"
1807
1808        if len(oneline) < 80:
1809            self.p(oneline)
1810            return
1811
1812        v = qual_ret
1813        if len(v) > 3:
1814            self.p(v)
1815            v = ''
1816        elif qual_ret[-1] != '*':
1817            v += ' '
1818        v += name + '('
1819        ind = '\t' * (len(v) // 8) + ' ' * (len(v) % 8)
1820        delta_ind = len(v) - len(ind)
1821        v += args[0]
1822        i = 1
1823        while i < len(args):
1824            next_len = len(v) + len(args[i])
1825            if v[0] == '\t':
1826                next_len += delta_ind
1827            if next_len > 76:
1828                self.p(v + ',')
1829                v = ind
1830            else:
1831                v += ', '
1832            v += args[i]
1833            i += 1
1834        self.p(v + ')' + suffix)
1835
1836    def write_func_lvar(self, local_vars):
1837        if not local_vars:
1838            return
1839
1840        if isinstance(local_vars, str):
1841            local_vars = [local_vars]
1842
1843        local_vars.sort(key=len, reverse=True)
1844        for var in local_vars:
1845            self.p(var)
1846        self.nl()
1847
1848    def write_func(self, qual_ret, name, body, args=None, local_vars=None):
1849        self.write_func_prot(qual_ret=qual_ret, name=name, args=args)
1850        self.block_start()
1851        self.write_func_lvar(local_vars=local_vars)
1852
1853        for line in body:
1854            self.p(line)
1855        self.block_end()
1856
1857    def writes_defines(self, defines):
1858        longest = 0
1859        for define in defines:
1860            longest = max(len(define[0]), longest)
1861        longest = ((longest + 8) // 8) * 8
1862        for define in defines:
1863            line = '#define ' + define[0]
1864            line += '\t' * ((longest - len(define[0]) + 7) // 8)
1865            if isinstance(define[1], int):
1866                line += str(define[1])
1867            elif isinstance(define[1], str):
1868                line += '"' + define[1] + '"'
1869            self.p(line)
1870
1871    def write_struct_init(self, members):
1872        longest = max(len(x[0]) for x in members)
1873        longest += 1  # because we prepend a .
1874        longest = ((longest + 8) // 8) * 8
1875        for one in members:
1876            line = '.' + one[0]
1877            line += '\t' * ((longest - len(one[0]) - 1 + 7) // 8)
1878            line += '= ' + str(one[1]) + ','
1879            self.p(line)
1880
1881    def ifdef_block(self, config):
1882        config_option = None
1883        if config:
1884            config_option = 'CONFIG_' + c_upper(config)
1885        if self._ifdef_block == config_option:
1886            return
1887
1888        if self._ifdef_block:
1889            self.p('#endif /* ' + self._ifdef_block + ' */')
1890        if config_option:
1891            self.p('#ifdef ' + config_option)
1892        self._ifdef_block = config_option
1893
1894
1895scalars = {'u8', 'u16', 'u32', 'u64', 's8', 's16', 's32', 's64', 'uint', 'sint'}
1896
1897direction_to_suffix = {
1898    'reply': '_rsp',
1899    'request': '_req',
1900    '': ''
1901}
1902
1903op_mode_to_wrapper = {
1904    'do': '',
1905    'dump': '_list',
1906    'notify': '_ntf',
1907    'event': '',
1908}
1909
1910_C_KW = {
1911    'auto',
1912    'bool',
1913    'break',
1914    'case',
1915    'char',
1916    'const',
1917    'continue',
1918    'default',
1919    'do',
1920    'double',
1921    'else',
1922    'enum',
1923    'extern',
1924    'float',
1925    'for',
1926    'goto',
1927    'if',
1928    'inline',
1929    'int',
1930    'long',
1931    'register',
1932    'return',
1933    'short',
1934    'signed',
1935    'sizeof',
1936    'static',
1937    'struct',
1938    'switch',
1939    'typedef',
1940    'union',
1941    'unsigned',
1942    'void',
1943    'volatile',
1944    'while'
1945}
1946
1947
1948def rdir(direction):
1949    if direction == 'reply':
1950        return 'request'
1951    if direction == 'request':
1952        return 'reply'
1953    return direction
1954
1955
1956def op_prefix(ri, direction, deref=False):
1957    suffix = f"_{ri.type_name}"
1958
1959    if not ri.op_mode:
1960        pass
1961    elif ri.op_mode == 'do':
1962        suffix += f"{direction_to_suffix[direction]}"
1963    else:
1964        if direction == 'request':
1965            suffix += '_req'
1966            if not ri.type_oneside:
1967                suffix += '_dump'
1968        else:
1969            if ri.type_consistent:
1970                if deref:
1971                    suffix += f"{direction_to_suffix[direction]}"
1972                else:
1973                    suffix += op_mode_to_wrapper[ri.op_mode]
1974            else:
1975                suffix += '_rsp'
1976                suffix += '_dump' if deref else '_list'
1977
1978    return f"{ri.family.c_name}{suffix}"
1979
1980
1981def type_name(ri, direction, deref=False):
1982    return f"struct {op_prefix(ri, direction, deref=deref)}"
1983
1984
1985def print_prototype(ri, direction, terminate=True, doc=None):
1986    suffix = ';' if terminate else ''
1987
1988    fname = ri.op.render_name
1989    if ri.op_mode == 'dump':
1990        fname += '_dump'
1991
1992    args = ['struct ynl_sock *ys']
1993    if 'request' in ri.op[ri.op_mode]:
1994        args.append(f"{type_name(ri, direction)} *" + f"{direction_to_suffix[direction][1:]}")
1995
1996    ret = 'int'
1997    if 'reply' in ri.op[ri.op_mode]:
1998        ret = f"{type_name(ri, rdir(direction))} *"
1999
2000    ri.cw.write_func_prot(ret, fname, args, doc=doc, suffix=suffix)
2001
2002
2003def print_req_prototype(ri):
2004    print_prototype(ri, "request", doc=ri.op['doc'])
2005
2006
2007def print_dump_prototype(ri):
2008    print_prototype(ri, "request")
2009
2010
2011def put_typol_submsg(cw, struct):
2012    cw.block_start(line=f'const struct ynl_policy_attr {struct.render_name}_policy[] =')
2013
2014    i = 0
2015    for name, arg in struct.member_list():
2016        nest = ""
2017        if arg.type == 'nest':
2018            nest = f" .nest = &{arg.nested_render_name}_nest,"
2019        cw.p('[%d] = { .type = YNL_PT_SUBMSG, .name = "%s",%s },' %
2020             (i, name, nest))
2021        i += 1
2022
2023    cw.block_end(line=';')
2024    cw.nl()
2025
2026    cw.block_start(line=f'const struct ynl_policy_nest {struct.render_name}_nest =')
2027    cw.p(f'.max_attr = {i - 1},')
2028    cw.p(f'.table = {struct.render_name}_policy,')
2029    cw.block_end(line=';')
2030    cw.nl()
2031
2032
2033def put_typol_fwd(cw, struct):
2034    cw.p(f'extern const struct ynl_policy_nest {struct.render_name}_nest;')
2035
2036
2037def put_typol(cw, struct):
2038    if struct.submsg:
2039        put_typol_submsg(cw, struct)
2040        return
2041
2042    type_max = struct.attr_set.max_name
2043    cw.block_start(line=f'const struct ynl_policy_attr {struct.render_name}_policy[{type_max} + 1] =')
2044
2045    for _, arg in struct.member_list():
2046        arg.attr_typol(cw)
2047
2048    cw.block_end(line=';')
2049    cw.nl()
2050
2051    cw.block_start(line=f'const struct ynl_policy_nest {struct.render_name}_nest =')
2052    cw.p(f'.max_attr = {type_max},')
2053    cw.p(f'.table = {struct.render_name}_policy,')
2054    cw.block_end(line=';')
2055    cw.nl()
2056
2057
2058def _put_enum_to_str_helper(cw, render_name, map_name, arg_name, enum=None):
2059    args = [f'int {arg_name}']
2060    if enum:
2061        args = [enum.user_type + ' ' + arg_name]
2062    cw.write_func_prot('const char *', f'{render_name}_str', args)
2063    cw.block_start()
2064    if enum and enum.type == 'flags':
2065        cw.p(f'{arg_name} = ffs({arg_name}) - 1;')
2066    cw.p(f'if ({arg_name} < 0 || {arg_name} >= (int)YNL_ARRAY_SIZE({map_name}))')
2067    cw.p('return NULL;')
2068    cw.p(f'return {map_name}[{arg_name}];')
2069    cw.block_end()
2070    cw.nl()
2071
2072
2073def put_op_name_fwd(family, cw):
2074    cw.write_func_prot('const char *', f'{family.c_name}_op_str', ['int op'], suffix=';')
2075
2076
2077def put_op_name(family, cw):
2078    map_name = f'{family.c_name}_op_strmap'
2079    cw.block_start(line=f"static const char * const {map_name}[] =")
2080    for op_name, op in family.msgs.items():
2081        if op.rsp_value:
2082            # Make sure we don't add duplicated entries, if multiple commands
2083            # produce the same response in legacy families.
2084            if family.rsp_by_value[op.rsp_value] != op:
2085                cw.p(f'// skip "{op_name}", duplicate reply value')
2086                continue
2087
2088            if op.req_value == op.rsp_value:
2089                cw.p(f'[{op.enum_name}] = "{op_name}",')
2090            else:
2091                cw.p(f'[{op.rsp_value}] = "{op_name}",')
2092    cw.block_end(line=';')
2093    cw.nl()
2094
2095    _put_enum_to_str_helper(cw, family.c_name + '_op', map_name, 'op')
2096
2097
2098def put_enum_to_str_fwd(_family, cw, enum):
2099    args = [enum.user_type + ' value']
2100    cw.write_func_prot('const char *', f'{enum.render_name}_str', args, suffix=';')
2101
2102
2103def put_enum_to_str(_family, cw, enum):
2104    map_name = f'{enum.render_name}_strmap'
2105    cw.block_start(line=f"static const char * const {map_name}[] =")
2106    for entry in enum.entries.values():
2107        cw.p(f'[{entry.value}] = "{entry.name}",')
2108    cw.block_end(line=';')
2109    cw.nl()
2110
2111    _put_enum_to_str_helper(cw, enum.render_name, map_name, 'value', enum=enum)
2112
2113
2114def put_local_vars(struct):
2115    local_vars = []
2116    has_array = False
2117    has_count = False
2118    for _, arg in struct.member_list():
2119        has_array |= arg.type == 'indexed-array'
2120        has_count |= arg.presence_type() == 'count'
2121    if has_array:
2122        local_vars.append('struct nlattr *array;')
2123    if has_count:
2124        local_vars.append('unsigned int i;')
2125    return local_vars
2126
2127
2128def put_req_nested_prototype(ri, struct, suffix=';'):
2129    func_args = ['struct nlmsghdr *nlh',
2130                 'unsigned int attr_type',
2131                 f'{struct.ptr_name}obj']
2132
2133    ri.cw.write_func_prot('int', f'{struct.render_name}_put', func_args,
2134                          suffix=suffix)
2135
2136
2137def put_req_nested(ri, struct):
2138    local_vars = []
2139    init_lines = []
2140
2141    if struct.submsg is None:
2142        local_vars.append('struct nlattr *nest;')
2143        init_lines.append("nest = ynl_attr_nest_start(nlh, attr_type);")
2144    if struct.fixed_header:
2145        local_vars.append('void *hdr;')
2146        struct_sz = f'sizeof({struct.fixed_header})'
2147        init_lines.append(f"hdr = ynl_nlmsg_put_extra_header(nlh, {struct_sz});")
2148        init_lines.append(f"memcpy(hdr, &obj->_hdr, {struct_sz});")
2149
2150    local_vars += put_local_vars(struct)
2151
2152    put_req_nested_prototype(ri, struct, suffix='')
2153    ri.cw.block_start()
2154    ri.cw.write_func_lvar(local_vars)
2155
2156    for line in init_lines:
2157        ri.cw.p(line)
2158
2159    for _, arg in struct.member_list():
2160        arg.attr_put(ri, "obj")
2161
2162    if struct.submsg is None:
2163        ri.cw.p("ynl_attr_nest_end(nlh, nest);")
2164
2165    ri.cw.nl()
2166    ri.cw.p('return 0;')
2167    ri.cw.block_end()
2168    ri.cw.nl()
2169
2170
2171def _multi_parse(ri, struct, init_lines, local_vars):
2172    if struct.fixed_header:
2173        local_vars += ['void *hdr;']
2174    if struct.nested:
2175        if struct.fixed_header:
2176            iter_line = f"ynl_attr_for_each_nested_off(attr, nested, sizeof({struct.fixed_header}))"
2177        else:
2178            iter_line = "ynl_attr_for_each_nested(attr, nested)"
2179    else:
2180        iter_line = "ynl_attr_for_each(attr, nlh, yarg->ys->family->hdr_len)"
2181        if ri.op.fixed_header != ri.family.fixed_header:
2182            if ri.family.is_classic():
2183                iter_line = f"ynl_attr_for_each(attr, nlh, sizeof({struct.fixed_header}))"
2184            else:
2185                raise Exception("Per-op fixed header not supported, yet")
2186
2187    indexed_arrays = set()
2188    multi_attrs = set()
2189    needs_parg = False
2190    var_set = set()
2191    for arg, aspec in struct.member_list():
2192        if aspec['type'] == 'indexed-array' and 'sub-type' in aspec:
2193            if aspec["sub-type"] in {'binary', 'nest'}:
2194                local_vars.append(f'const struct nlattr *attr_{aspec.c_name} = NULL;')
2195                indexed_arrays.add(arg)
2196            elif aspec['sub-type'] in scalars:
2197                local_vars.append(f'const struct nlattr *attr_{aspec.c_name} = NULL;')
2198                indexed_arrays.add(arg)
2199            else:
2200                raise Exception(f'Not supported sub-type {aspec["sub-type"]}')
2201        if 'multi-attr' in aspec:
2202            multi_attrs.add(arg)
2203        needs_parg |= 'nested-attributes' in aspec
2204        needs_parg |= 'sub-message' in aspec
2205
2206        try:
2207            _, _, l_vars = aspec._attr_get(ri, '')
2208            var_set |= set(l_vars) if l_vars else set()
2209        except Exception:
2210            pass  # _attr_get() not implemented by simple types, ignore
2211    local_vars += list(var_set)
2212    if indexed_arrays or multi_attrs:
2213        local_vars.append('int i;')
2214    if needs_parg:
2215        local_vars.append('struct ynl_parse_arg parg;')
2216        init_lines.append('parg.ys = yarg->ys;')
2217
2218    all_multi = indexed_arrays | multi_attrs
2219
2220    for arg in sorted(all_multi):
2221        local_vars.append(f"unsigned int n_{struct[arg].c_name} = 0;")
2222
2223    ri.cw.block_start()
2224    ri.cw.write_func_lvar(local_vars)
2225
2226    for line in init_lines:
2227        ri.cw.p(line)
2228    ri.cw.nl()
2229
2230    for arg in struct.inherited:
2231        ri.cw.p(f'dst->{arg} = {arg};')
2232
2233    if struct.fixed_header:
2234        if struct.nested:
2235            ri.cw.p('hdr = ynl_attr_data(nested);')
2236        elif ri.family.is_classic():
2237            ri.cw.p('hdr = ynl_nlmsg_data(nlh);')
2238        else:
2239            ri.cw.p('hdr = ynl_nlmsg_data_offset(nlh, sizeof(struct genlmsghdr));')
2240        ri.cw.p(f"memcpy(&dst->_hdr, hdr, sizeof({struct.fixed_header}));")
2241    for arg in sorted(all_multi):
2242        aspec = struct[arg]
2243        ri.cw.p(f"if (dst->{aspec.c_name})")
2244        ri.cw.p(f'return ynl_error_parse(yarg, "attribute already present ({struct.attr_set.name}.{aspec.name})");')
2245
2246    ri.cw.nl()
2247    ri.cw.block_start(line=iter_line)
2248    ri.cw.p('unsigned int type = ynl_attr_type(attr);')
2249    ri.cw.nl()
2250
2251    first = True
2252    for _, arg in struct.member_list():
2253        good = arg.attr_get(ri, 'dst', first=first)
2254        # First may be 'unused' or 'pad', ignore those
2255        first &= not good
2256
2257    ri.cw.block_end()
2258    ri.cw.nl()
2259
2260    for arg in sorted(indexed_arrays):
2261        aspec = struct[arg]
2262
2263        ri.cw.block_start(line=f"if (n_{aspec.c_name})")
2264        ri.cw.p(f"dst->{aspec.c_name} = calloc(n_{aspec.c_name}, sizeof(*dst->{aspec.c_name}));")
2265        ri.cw.p(f"if (!dst->{aspec.c_name})")
2266        ri.cw.p("return YNL_PARSE_CB_ERROR;")
2267        ri.cw.p(f"dst->_count.{aspec.c_name} = n_{aspec.c_name};")
2268        ri.cw.p('i = 0;')
2269        if 'nested-attributes' in aspec:
2270            ri.cw.p(f"parg.rsp_policy = &{aspec.nested_render_name}_nest;")
2271        ri.cw.block_start(line=f"ynl_attr_for_each_nested(attr, attr_{aspec.c_name})")
2272        if 'nested-attributes' in aspec:
2273            ri.cw.p(f"parg.data = &dst->{aspec.c_name}[i];")
2274            ri.cw.p(f"if ({aspec.nested_render_name}_parse(&parg, attr, ynl_attr_type(attr)))")
2275            ri.cw.p('return YNL_PARSE_CB_ERROR;')
2276        elif aspec.sub_type in scalars:
2277            ri.cw.p(f"dst->{aspec.c_name}[i] = ynl_attr_get_{aspec.sub_type}(attr);")
2278        elif aspec.sub_type == 'binary' and 'exact-len' in aspec.checks:
2279            # Length is validated by typol
2280            ri.cw.p(f'memcpy(dst->{aspec.c_name}[i], ynl_attr_data(attr), {aspec.checks["exact-len"]});')
2281        else:
2282            raise Exception(f"Nest parsing type not supported in {aspec['name']}")
2283        ri.cw.p('i++;')
2284        ri.cw.block_end()
2285        ri.cw.block_end()
2286    ri.cw.nl()
2287
2288    for arg in sorted(multi_attrs):
2289        aspec = struct[arg]
2290        ri.cw.block_start(line=f"if (n_{aspec.c_name})")
2291        ri.cw.p(f"dst->{aspec.c_name} = calloc(n_{aspec.c_name}, sizeof(*dst->{aspec.c_name}));")
2292        ri.cw.p(f"if (!dst->{aspec.c_name})")
2293        ri.cw.p("return YNL_PARSE_CB_ERROR;")
2294        ri.cw.p(f"dst->_count.{aspec.c_name} = n_{aspec.c_name};")
2295        ri.cw.p('i = 0;')
2296        if 'nested-attributes' in aspec:
2297            ri.cw.p(f"parg.rsp_policy = &{aspec.nested_render_name}_nest;")
2298        ri.cw.block_start(line=iter_line)
2299        ri.cw.block_start(line=f"if (ynl_attr_type(attr) == {aspec.enum_name})")
2300        if 'nested-attributes' in aspec:
2301            ri.cw.p(f"parg.data = &dst->{aspec.c_name}[i];")
2302            ri.cw.p(f"if ({aspec.nested_render_name}_parse(&parg, attr))")
2303            ri.cw.p('return YNL_PARSE_CB_ERROR;')
2304        elif aspec.type in scalars:
2305            ri.cw.p(f"dst->{aspec.c_name}[i] = ynl_attr_get_{aspec.type}(attr);")
2306        elif aspec.type == 'binary' and 'struct' in aspec:
2307            ri.cw.p('size_t len = ynl_attr_data_len(attr);')
2308            ri.cw.nl()
2309            ri.cw.p(f'if (len > sizeof(dst->{aspec.c_name}[0]))')
2310            ri.cw.p(f'len = sizeof(dst->{aspec.c_name}[0]);')
2311            ri.cw.p(f"memcpy(&dst->{aspec.c_name}[i], ynl_attr_data(attr), len);")
2312        elif aspec.type == 'string':
2313            ri.cw.p('unsigned int len;')
2314            ri.cw.nl()
2315            ri.cw.p('len = strnlen(ynl_attr_get_str(attr), ynl_attr_data_len(attr));')
2316            ri.cw.p(f'dst->{aspec.c_name}[i] = malloc(sizeof(struct ynl_string) + len + 1);')
2317            ri.cw.p(f"if (!dst->{aspec.c_name}[i])")
2318            ri.cw.p("return YNL_PARSE_CB_ERROR;")
2319            ri.cw.p(f"dst->{aspec.c_name}[i]->len = len;")
2320            ri.cw.p(f"memcpy(dst->{aspec.c_name}[i]->str, ynl_attr_get_str(attr), len);")
2321            ri.cw.p(f"dst->{aspec.c_name}[i]->str[len] = 0;")
2322        else:
2323            raise Exception(f'Nest parsing of type {aspec.type} not supported yet')
2324        ri.cw.p('i++;')
2325        ri.cw.block_end()
2326        ri.cw.block_end()
2327        ri.cw.block_end()
2328    ri.cw.nl()
2329
2330    if struct.nested:
2331        ri.cw.p('return 0;')
2332    else:
2333        ri.cw.p('return YNL_PARSE_CB_OK;')
2334    ri.cw.block_end()
2335    ri.cw.nl()
2336
2337
2338def parse_rsp_submsg(ri, struct):
2339    parse_rsp_nested_prototype(ri, struct, suffix='')
2340
2341    var = 'dst'
2342    local_vars = {'const struct nlattr *attr = nested;',
2343                  f'{struct.ptr_name}{var} = yarg->data;',
2344                  'struct ynl_parse_arg parg;'}
2345
2346    for _, arg in struct.member_list():
2347        _, _, l_vars = arg._attr_get(ri, var)
2348        local_vars |= set(l_vars) if l_vars else set()
2349
2350    ri.cw.block_start()
2351    ri.cw.write_func_lvar(list(local_vars))
2352    ri.cw.p('parg.ys = yarg->ys;')
2353    ri.cw.nl()
2354
2355    first = True
2356    for name, arg in struct.member_list():
2357        kw = 'if' if first else 'else if'
2358        first = False
2359
2360        ri.cw.block_start(line=f'{kw} (!strcmp(sel, "{name}"))')
2361        get_lines, init_lines, _ = arg._attr_get(ri, var)
2362        for line in init_lines or []:
2363            ri.cw.p(line)
2364        for line in get_lines:
2365            ri.cw.p(line)
2366        if arg.presence_type() == 'present':
2367            ri.cw.p(f"{var}->_present.{arg.c_name} = 1;")
2368        ri.cw.block_end()
2369    ri.cw.p('return 0;')
2370    ri.cw.block_end()
2371    ri.cw.nl()
2372
2373
2374def parse_rsp_nested_prototype(ri, struct, suffix=';'):
2375    func_args = ['struct ynl_parse_arg *yarg',
2376                 'const struct nlattr *nested']
2377    for sel in struct.external_selectors():
2378        func_args.append('const char *_sel_' + sel.name)
2379    if struct.submsg:
2380        func_args.insert(1, 'const char *sel')
2381    for arg in struct.inherited:
2382        func_args.append('__u32 ' + arg)
2383
2384    ri.cw.write_func_prot('int', f'{struct.render_name}_parse', func_args,
2385                          suffix=suffix)
2386
2387
2388def parse_rsp_nested(ri, struct):
2389    if struct.submsg:
2390        parse_rsp_submsg(ri, struct)
2391        return
2392
2393    parse_rsp_nested_prototype(ri, struct, suffix='')
2394
2395    local_vars = ['const struct nlattr *attr;',
2396                  f'{struct.ptr_name}dst = yarg->data;']
2397    init_lines = []
2398
2399    if struct.member_list():
2400        _multi_parse(ri, struct, init_lines, local_vars)
2401    else:
2402        # Empty nest
2403        ri.cw.block_start()
2404        ri.cw.p('return 0;')
2405        ri.cw.block_end()
2406        ri.cw.nl()
2407
2408
2409def parse_rsp_msg(ri, deref=False):
2410    if 'reply' not in ri.op[ri.op_mode] and ri.op_mode != 'event':
2411        return
2412
2413    func_args = ['const struct nlmsghdr *nlh',
2414                 'struct ynl_parse_arg *yarg']
2415
2416    local_vars = [f'{type_name(ri, "reply", deref=deref)} *dst;',
2417                  'const struct nlattr *attr;']
2418    init_lines = ['dst = yarg->data;']
2419
2420    ri.cw.write_func_prot('int', f'{op_prefix(ri, "reply", deref=deref)}_parse', func_args)
2421
2422    if ri.struct["reply"].member_list():
2423        _multi_parse(ri, ri.struct["reply"], init_lines, local_vars)
2424    else:
2425        # Empty reply
2426        ri.cw.block_start()
2427        ri.cw.p('return YNL_PARSE_CB_OK;')
2428        ri.cw.block_end()
2429        ri.cw.nl()
2430
2431
2432def print_req(ri):
2433    ret_ok = '0'
2434    ret_err = '-1'
2435    direction = "request"
2436    local_vars = ['struct ynl_req_state yrs = { .yarg = { .ys = ys, }, };',
2437                  'struct nlmsghdr *nlh;',
2438                  'int err;']
2439
2440    if 'reply' in ri.op[ri.op_mode]:
2441        ret_ok = 'rsp'
2442        ret_err = 'NULL'
2443        local_vars += [f'{type_name(ri, rdir(direction))} *rsp;']
2444
2445    if ri.struct["request"].fixed_header:
2446        local_vars += ['size_t hdr_len;',
2447                       'void *hdr;']
2448
2449    local_vars += put_local_vars(ri.struct['request'])
2450
2451    print_prototype(ri, direction, terminate=False)
2452    ri.cw.block_start()
2453    ri.cw.write_func_lvar(local_vars)
2454
2455    if ri.family.is_classic():
2456        ri.cw.p(f"nlh = ynl_msg_start_req(ys, {ri.op.enum_name}, req->_nlmsg_flags);")
2457    else:
2458        ri.cw.p(f"nlh = ynl_gemsg_start_req(ys, {ri.nl.get_family_id()}, {ri.op.enum_name}, 1);")
2459
2460    ri.cw.p(f"ys->req_policy = &{ri.struct['request'].render_name}_nest;")
2461    ri.cw.p(f"ys->req_hdr_len = {ri.fixed_hdr_len};")
2462    if 'reply' in ri.op[ri.op_mode]:
2463        ri.cw.p(f"yrs.yarg.rsp_policy = &{ri.struct['reply'].render_name}_nest;")
2464    ri.cw.nl()
2465
2466    if ri.struct['request'].fixed_header:
2467        ri.cw.p("hdr_len = sizeof(req->_hdr);")
2468        ri.cw.p("hdr = ynl_nlmsg_put_extra_header(nlh, hdr_len);")
2469        ri.cw.p("memcpy(hdr, &req->_hdr, hdr_len);")
2470        ri.cw.nl()
2471
2472    for _, attr in ri.struct["request"].member_list():
2473        attr.attr_put(ri, "req")
2474    ri.cw.nl()
2475
2476    if 'reply' in ri.op[ri.op_mode]:
2477        ri.cw.p('rsp = calloc(1, sizeof(*rsp));')
2478        ri.cw.p('if (!rsp)')
2479        ri.cw.p(f'return {ret_err};')
2480        ri.cw.p('yrs.yarg.data = rsp;')
2481        ri.cw.p(f"yrs.cb = {op_prefix(ri, 'reply')}_parse;")
2482        if ri.op.value is not None:
2483            ri.cw.p(f'yrs.rsp_cmd = {ri.op.enum_name};')
2484        else:
2485            ri.cw.p(f'yrs.rsp_cmd = {ri.op.rsp_value};')
2486        ri.cw.nl()
2487    ri.cw.p("err = ynl_exec(ys, nlh, &yrs);")
2488    ri.cw.p('if (err < 0)')
2489    if 'reply' in ri.op[ri.op_mode]:
2490        ri.cw.p('goto err_free;')
2491    else:
2492        ri.cw.p('return -1;')
2493    ri.cw.nl()
2494
2495    ri.cw.p(f"return {ret_ok};")
2496    ri.cw.nl()
2497
2498    if 'reply' in ri.op[ri.op_mode]:
2499        ri.cw.p('err_free:')
2500        ri.cw.p(f"{call_free(ri, rdir(direction), 'rsp')}")
2501        ri.cw.p(f"return {ret_err};")
2502
2503    ri.cw.block_end()
2504
2505
2506def print_dump(ri):
2507    direction = "request"
2508    print_prototype(ri, direction, terminate=False)
2509    ri.cw.block_start()
2510    local_vars = ['struct ynl_dump_state yds = {};',
2511                  'struct nlmsghdr *nlh;',
2512                  'int err;']
2513
2514    if ri.struct['request'].fixed_header:
2515        local_vars += ['size_t hdr_len;',
2516                       'void *hdr;']
2517
2518    if 'request' in ri.op[ri.op_mode]:
2519        local_vars += put_local_vars(ri.struct['request'])
2520
2521    ri.cw.write_func_lvar(local_vars)
2522
2523    ri.cw.p('yds.yarg.ys = ys;')
2524    ri.cw.p(f"yds.yarg.rsp_policy = &{ri.struct['reply'].render_name}_nest;")
2525    ri.cw.p("yds.yarg.data = NULL;")
2526    ri.cw.p(f"yds.alloc_sz = sizeof({type_name(ri, rdir(direction))});")
2527    ri.cw.p(f"yds.cb = {op_prefix(ri, 'reply', deref=True)}_parse;")
2528    if ri.op.value is not None:
2529        ri.cw.p(f'yds.rsp_cmd = {ri.op.enum_name};')
2530    else:
2531        ri.cw.p(f'yds.rsp_cmd = {ri.op.rsp_value};')
2532    ri.cw.nl()
2533    if ri.family.is_classic():
2534        ri.cw.p(f"nlh = ynl_msg_start_dump(ys, {ri.op.enum_name});")
2535    else:
2536        ri.cw.p(f"nlh = ynl_gemsg_start_dump(ys, {ri.nl.get_family_id()}, {ri.op.enum_name}, 1);")
2537
2538    if ri.struct['request'].fixed_header:
2539        ri.cw.p("hdr_len = sizeof(req->_hdr);")
2540        ri.cw.p("hdr = ynl_nlmsg_put_extra_header(nlh, hdr_len);")
2541        ri.cw.p("memcpy(hdr, &req->_hdr, hdr_len);")
2542        ri.cw.nl()
2543
2544    if "request" in ri.op[ri.op_mode]:
2545        ri.cw.p(f"ys->req_policy = &{ri.struct['request'].render_name}_nest;")
2546        ri.cw.p(f"ys->req_hdr_len = {ri.fixed_hdr_len};")
2547        ri.cw.nl()
2548        for _, attr in ri.struct["request"].member_list():
2549            attr.attr_put(ri, "req")
2550    ri.cw.nl()
2551
2552    ri.cw.p('err = ynl_exec_dump(ys, nlh, &yds);')
2553    ri.cw.p('if (err < 0)')
2554    ri.cw.p('goto free_list;')
2555    ri.cw.nl()
2556
2557    ri.cw.p('return yds.first;')
2558    ri.cw.nl()
2559    ri.cw.p('free_list:')
2560    ri.cw.p(call_free(ri, rdir(direction), 'yds.first'))
2561    ri.cw.p('return NULL;')
2562    ri.cw.block_end()
2563
2564
2565def call_free(ri, direction, var):
2566    return f"{op_prefix(ri, direction)}_free({var});"
2567
2568
2569def free_arg_name(direction):
2570    if direction:
2571        return direction_to_suffix[direction][1:]
2572    return 'obj'
2573
2574
2575def print_alloc_wrapper(ri, direction, struct=None):
2576    name = op_prefix(ri, direction)
2577    struct_name = name
2578    if ri.type_name_conflict:
2579        struct_name += '_'
2580
2581    args = ["void"]
2582    cnt = "1"
2583    if struct and struct.in_multi_val:
2584        args = ["unsigned int n"]
2585        cnt = "n"
2586
2587    ri.cw.write_func_prot(f'static inline struct {struct_name} *',
2588                          f"{name}_alloc", args)
2589    ri.cw.block_start()
2590    ri.cw.p(f'return calloc({cnt}, sizeof(struct {struct_name}));')
2591    ri.cw.block_end()
2592
2593
2594def print_free_prototype(ri, direction, suffix=';'):
2595    name = op_prefix(ri, direction)
2596    struct_name = name
2597    if ri.type_name_conflict:
2598        struct_name += '_'
2599    arg = free_arg_name(direction)
2600    ri.cw.write_func_prot('void', f"{name}_free", [f"struct {struct_name} *{arg}"], suffix=suffix)
2601
2602
2603def print_nlflags_set(ri, direction):
2604    name = op_prefix(ri, direction)
2605    ri.cw.write_func_prot('static inline void', f"{name}_set_nlflags",
2606                          [f"struct {name} *req", "__u16 nl_flags"])
2607    ri.cw.block_start()
2608    ri.cw.p('req->_nlmsg_flags = nl_flags;')
2609    ri.cw.block_end()
2610    ri.cw.nl()
2611
2612
2613def _print_type(ri, direction, struct):
2614    suffix = f'_{ri.type_name}{direction_to_suffix[direction]}'
2615    if not direction and ri.type_name_conflict:
2616        suffix += '_'
2617
2618    if ri.op_mode == 'dump' and not ri.type_oneside:
2619        suffix += '_dump'
2620
2621    ri.cw.block_start(line=f"struct {ri.family.c_name}{suffix}")
2622
2623    if ri.needs_nlflags(direction):
2624        ri.cw.p('__u16 _nlmsg_flags;')
2625        ri.cw.nl()
2626    if struct.fixed_header:
2627        ri.cw.p(struct.fixed_header + ' _hdr;')
2628        ri.cw.nl()
2629
2630    for type_filter in ['present', 'len', 'count']:
2631        meta_started = False
2632        for _, attr in struct.member_list():
2633            line = attr.presence_member(ri.ku_space, type_filter)
2634            if line:
2635                if not meta_started:
2636                    ri.cw.block_start(line="struct")
2637                    meta_started = True
2638                ri.cw.p(line)
2639        if meta_started:
2640            ri.cw.block_end(line=f'_{type_filter};')
2641    ri.cw.nl()
2642
2643    for arg in struct.inherited:
2644        ri.cw.p(f"__u32 {arg};")
2645
2646    for _, attr in struct.member_list():
2647        attr.struct_member(ri)
2648
2649    ri.cw.block_end(line=';')
2650    ri.cw.nl()
2651
2652
2653def print_type(ri, direction):
2654    _print_type(ri, direction, ri.struct[direction])
2655
2656
2657def print_type_full(ri, struct):
2658    _print_type(ri, "", struct)
2659
2660    if struct.request and struct.in_multi_val:
2661        print_alloc_wrapper(ri, "", struct)
2662        ri.cw.nl()
2663        free_rsp_nested_prototype(ri)
2664        ri.cw.nl()
2665
2666        # Name conflicts are too hard to deal with with the current code base,
2667        # they are very rare so don't bother printing setters in that case.
2668        if ri.ku_space == 'user' and not ri.type_name_conflict:
2669            for _, attr in struct.member_list():
2670                attr.setter(ri, ri.attr_set, "", var="obj")
2671        ri.cw.nl()
2672
2673
2674def print_type_helpers(ri, direction, deref=False):
2675    print_free_prototype(ri, direction)
2676    ri.cw.nl()
2677
2678    if ri.needs_nlflags(direction):
2679        print_nlflags_set(ri, direction)
2680
2681    if ri.ku_space == 'user' and direction == 'request':
2682        for _, attr in ri.struct[direction].member_list():
2683            attr.setter(ri, ri.attr_set, direction, deref=deref)
2684    ri.cw.nl()
2685
2686
2687def print_req_type_helpers(ri):
2688    if ri.type_empty("request"):
2689        return
2690    print_alloc_wrapper(ri, "request")
2691    print_type_helpers(ri, "request")
2692
2693
2694def print_rsp_type_helpers(ri):
2695    if 'reply' not in ri.op[ri.op_mode]:
2696        return
2697    print_type_helpers(ri, "reply")
2698
2699
2700def print_parse_prototype(ri, direction, terminate=True):
2701    suffix = "_rsp" if direction == "reply" else "_req"
2702    term = ';' if terminate else ''
2703
2704    ri.cw.write_func_prot('void', f"{ri.op.render_name}{suffix}_parse",
2705                          ['const struct nlattr **tb',
2706                           f"struct {ri.op.render_name}{suffix} *req"],
2707                          suffix=term)
2708
2709
2710def print_req_type(ri):
2711    if ri.type_empty("request"):
2712        return
2713    print_type(ri, "request")
2714
2715
2716def print_req_free(ri):
2717    if 'request' not in ri.op[ri.op_mode]:
2718        return
2719    _free_type(ri, 'request', ri.struct['request'])
2720
2721
2722def print_rsp_type(ri):
2723    if ri.op_mode in ('do', 'dump') and 'reply' in ri.op[ri.op_mode]:
2724        direction = 'reply'
2725    elif ri.op_mode == 'event':
2726        direction = 'reply'
2727    else:
2728        return
2729    print_type(ri, direction)
2730
2731
2732def print_wrapped_type(ri):
2733    ri.cw.block_start(line=f"{type_name(ri, 'reply')}")
2734    if ri.op_mode == 'dump':
2735        ri.cw.p(f"{type_name(ri, 'reply')} *next;")
2736    elif ri.op_mode in ('notify', 'event'):
2737        ri.cw.p('__u16 family;')
2738        ri.cw.p('__u8 cmd;')
2739        ri.cw.p('struct ynl_ntf_base_type *next;')
2740        ri.cw.p(f"void (*free)({type_name(ri, 'reply')} *ntf);")
2741    ri.cw.p(f"{type_name(ri, 'reply', deref=True)} obj __attribute__((aligned(8)));")
2742    ri.cw.block_end(line=';')
2743    ri.cw.nl()
2744    print_free_prototype(ri, 'reply')
2745    ri.cw.nl()
2746
2747
2748def _free_type_members_iter(ri, struct):
2749    if struct.free_needs_iter():
2750        ri.cw.p('unsigned int i;')
2751        ri.cw.nl()
2752
2753
2754def _free_type_members(ri, var, struct, ref=''):
2755    for _, attr in struct.member_list():
2756        attr.free(ri, var, ref)
2757
2758
2759def _free_type(ri, direction, struct):
2760    var = free_arg_name(direction)
2761
2762    print_free_prototype(ri, direction, suffix='')
2763    ri.cw.block_start()
2764    _free_type_members_iter(ri, struct)
2765    _free_type_members(ri, var, struct)
2766    if direction:
2767        ri.cw.p(f'free({var});')
2768    ri.cw.block_end()
2769    ri.cw.nl()
2770
2771
2772def free_rsp_nested_prototype(ri):
2773    print_free_prototype(ri, "")
2774
2775
2776def free_rsp_nested(ri, struct):
2777    _free_type(ri, "", struct)
2778
2779
2780def print_rsp_free(ri):
2781    if 'reply' not in ri.op[ri.op_mode]:
2782        return
2783    _free_type(ri, 'reply', ri.struct['reply'])
2784
2785
2786def print_dump_type_free(ri):
2787    sub_type = type_name(ri, 'reply')
2788
2789    print_free_prototype(ri, 'reply', suffix='')
2790    ri.cw.block_start()
2791    ri.cw.p(f"{sub_type} *next = rsp;")
2792    ri.cw.nl()
2793    ri.cw.p('if (!next)')
2794    ri.cw.p('return;')
2795    ri.cw.nl()
2796    ri.cw.block_start(line='while ((void *)next != YNL_LIST_END)')
2797    _free_type_members_iter(ri, ri.struct['reply'])
2798    ri.cw.p('rsp = next;')
2799    ri.cw.p('next = rsp->next;')
2800    ri.cw.nl()
2801
2802    _free_type_members(ri, 'rsp', ri.struct['reply'], ref='obj.')
2803    ri.cw.p('free(rsp);')
2804    ri.cw.block_end()
2805    ri.cw.block_end()
2806    ri.cw.nl()
2807
2808
2809def print_ntf_type_free(ri):
2810    print_free_prototype(ri, 'reply', suffix='')
2811    ri.cw.block_start()
2812    _free_type_members_iter(ri, ri.struct['reply'])
2813    _free_type_members(ri, 'rsp', ri.struct['reply'], ref='obj.')
2814    ri.cw.p('free(rsp);')
2815    ri.cw.block_end()
2816    ri.cw.nl()
2817
2818
2819def print_req_policy_fwd(cw, struct, ri=None, terminate=True):
2820    if terminate and ri and policy_should_be_static(struct.family):
2821        return
2822
2823    if terminate:
2824        prefix = 'extern '
2825    else:
2826        if ri and policy_should_be_static(struct.family):
2827            prefix = 'static '
2828        else:
2829            prefix = ''
2830
2831    suffix = ';' if terminate else ' = {'
2832
2833    max_attr = struct.attr_max_val
2834    if ri:
2835        name = ri.op.render_name
2836        if ri.op.dual_policy:
2837            name += '_' + ri.op_mode
2838    else:
2839        name = struct.render_name
2840    cw.p(f"{prefix}const struct nla_policy {name}_nl_policy[{max_attr.enum_name} + 1]{suffix}")
2841
2842
2843def print_req_policy(cw, struct, ri=None):
2844    if ri and ri.op:
2845        cw.ifdef_block(ri.op.get('config-cond', None))
2846    print_req_policy_fwd(cw, struct, ri=ri, terminate=False)
2847    for _, arg in struct.member_list():
2848        arg.attr_policy(cw)
2849    cw.p("};")
2850    cw.ifdef_block(None)
2851    cw.nl()
2852
2853
2854def kernel_can_gen_family_struct(family):
2855    return family.proto == 'genetlink'
2856
2857
2858def policy_should_be_static(family):
2859    return family.kernel_policy == 'split' or kernel_can_gen_family_struct(family)
2860
2861
2862def print_kernel_policy_ranges(family, cw):
2863    first = True
2864    for _, attr_set in family.attr_sets.items():
2865        if attr_set.subset_of:
2866            continue
2867
2868        for _, attr in attr_set.items():
2869            if not attr.request:
2870                continue
2871            if 'full-range' not in attr.checks:
2872                continue
2873
2874            if first:
2875                cw.p('/* Integer value ranges */')
2876                first = False
2877
2878            sign = '' if attr.type[0] == 'u' else '_signed'
2879            suffix = 'ULL' if attr.type[0] == 'u' else 'LL'
2880            cw.block_start(line=f'static const struct netlink_range_validation{sign} {c_lower(attr.enum_name)}_range =')
2881            members = []
2882            if 'min' in attr.checks:
2883                members.append(('min', attr.get_limit_str('min', suffix=suffix)))
2884            if 'max' in attr.checks:
2885                members.append(('max', attr.get_limit_str('max', suffix=suffix)))
2886            cw.write_struct_init(members)
2887            cw.block_end(line=';')
2888            cw.nl()
2889
2890
2891def print_kernel_policy_sparse_enum_validates(family, cw):
2892    first = True
2893    for _, attr_set in family.attr_sets.items():
2894        if attr_set.subset_of:
2895            continue
2896
2897        for _, attr in attr_set.items():
2898            if not attr.request:
2899                continue
2900            if not attr.enum_name:
2901                continue
2902            if 'sparse' not in attr.checks:
2903                continue
2904
2905            if first:
2906                cw.p('/* Sparse enums validation callbacks */')
2907                first = False
2908
2909            cw.write_func_prot('static int', f'{c_lower(attr.enum_name)}_validate',
2910                               ['const struct nlattr *attr', 'struct netlink_ext_ack *extack'])
2911            cw.block_start()
2912            cw.block_start(line=f'switch (nla_get_{attr["type"]}(attr))')
2913            enum = family.consts[attr['enum']]
2914            first_entry = True
2915            for entry in enum.entries.values():
2916                if first_entry:
2917                    first_entry = False
2918                else:
2919                    cw.p('fallthrough;')
2920                cw.p(f'case {entry.c_name}:')
2921            cw.p('return 0;')
2922            cw.block_end()
2923            cw.p('NL_SET_ERR_MSG_ATTR(extack, attr, "invalid enum value");')
2924            cw.p('return -EINVAL;')
2925            cw.block_end()
2926            cw.nl()
2927
2928
2929def print_kernel_op_table_fwd(family, cw, terminate):
2930    exported = not kernel_can_gen_family_struct(family)
2931
2932    if not terminate or exported:
2933        cw.p(f"/* Ops table for {family.ident_name} */")
2934
2935        pol_to_struct = {'global': 'genl_small_ops',
2936                         'per-op': 'genl_ops',
2937                         'split': 'genl_split_ops'}
2938        struct_type = pol_to_struct[family.kernel_policy]
2939
2940        if not exported:
2941            cnt = ""
2942        elif family.kernel_policy == 'split':
2943            cnt = 0
2944            for op in family.ops.values():
2945                if 'do' in op:
2946                    cnt += 1
2947                if 'dump' in op:
2948                    cnt += 1
2949        else:
2950            cnt = len(family.ops)
2951
2952        qual = 'static const' if not exported else 'const'
2953        line = f"{qual} struct {struct_type} {family.c_name}_nl_ops[{cnt}]"
2954        if terminate:
2955            cw.p(f"extern {line};")
2956        else:
2957            cw.block_start(line=line + ' =')
2958
2959    if not terminate:
2960        return
2961
2962    cw.nl()
2963    for name in family.hooks['pre']['do']['list']:
2964        cw.write_func_prot('int', c_lower(name),
2965                           ['const struct genl_split_ops *ops',
2966                            'struct sk_buff *skb', 'struct genl_info *info'], suffix=';')
2967    for name in family.hooks['post']['do']['list']:
2968        cw.write_func_prot('void', c_lower(name),
2969                           ['const struct genl_split_ops *ops',
2970                            'struct sk_buff *skb', 'struct genl_info *info'], suffix=';')
2971    for name in family.hooks['pre']['dump']['list']:
2972        cw.write_func_prot('int', c_lower(name),
2973                           ['struct netlink_callback *cb'], suffix=';')
2974    for name in family.hooks['post']['dump']['list']:
2975        cw.write_func_prot('int', c_lower(name),
2976                           ['struct netlink_callback *cb'], suffix=';')
2977
2978    cw.nl()
2979
2980    for op_name, op in family.ops.items():
2981        if op.is_async:
2982            continue
2983
2984        if 'do' in op:
2985            name = c_lower(f"{family.fn_prefix}-{op_name}-doit")
2986            cw.write_func_prot('int', name,
2987                               ['struct sk_buff *skb', 'struct genl_info *info'], suffix=';')
2988
2989        if 'dump' in op:
2990            name = c_lower(f"{family.fn_prefix}-{op_name}-dumpit")
2991            cw.write_func_prot('int', name,
2992                               ['struct sk_buff *skb', 'struct netlink_callback *cb'], suffix=';')
2993    cw.nl()
2994
2995
2996def print_kernel_op_table_hdr(family, cw):
2997    print_kernel_op_table_fwd(family, cw, terminate=True)
2998
2999
3000def print_kernel_op_table(family, cw):
3001    print_kernel_op_table_fwd(family, cw, terminate=False)
3002    if family.kernel_policy in ('global', 'per-op'):
3003        for op_name, op in family.ops.items():
3004            if op.is_async:
3005                continue
3006
3007            cw.ifdef_block(op.get('config-cond', None))
3008            cw.block_start()
3009            members = [('cmd', op.enum_name)]
3010            if 'dont-validate' in op:
3011                members.append(('validate',
3012                                ' | '.join([c_upper('genl-dont-validate-' + x)
3013                                            for x in op['dont-validate']])), )
3014            for op_mode in ['do', 'dump']:
3015                if op_mode in op:
3016                    name = c_lower(f"{family.fn_prefix}-{op_name}-{op_mode}it")
3017                    members.append((op_mode + 'it', name))
3018            if family.kernel_policy == 'per-op':
3019                struct = Struct(family, op['attribute-set'],
3020                                type_list=op['do']['request']['attributes'])
3021
3022                name = c_lower(f"{family.ident_name}-{op_name}-nl-policy")
3023                members.append(('policy', name))
3024                members.append(('maxattr', struct.attr_max_val.enum_name))
3025            if 'flags' in op:
3026                members.append(('flags', ' | '.join([c_upper('genl-' + x) for x in op['flags']])))
3027            cw.write_struct_init(members)
3028            cw.block_end(line=',')
3029    elif family.kernel_policy == 'split':
3030        cb_names = {'do':   {'pre': 'pre_doit', 'post': 'post_doit'},
3031                    'dump': {'pre': 'start', 'post': 'done'}}
3032
3033        for op_name, op in family.ops.items():
3034            for op_mode in ['do', 'dump']:
3035                if op.is_async or op_mode not in op:
3036                    continue
3037
3038                cw.ifdef_block(op.get('config-cond', None))
3039                cw.block_start()
3040                members = [('cmd', op.enum_name)]
3041                if 'dont-validate' in op:
3042                    dont_validate = []
3043                    for x in op['dont-validate']:
3044                        if op_mode == 'do' and x in ['dump', 'dump-strict']:
3045                            continue
3046                        if op_mode == "dump" and x == 'strict':
3047                            continue
3048                        dont_validate.append(x)
3049
3050                    if dont_validate:
3051                        members.append(('validate',
3052                                        ' | '.join([c_upper('genl-dont-validate-' + x)
3053                                                    for x in dont_validate])), )
3054                name = c_lower(f"{family.fn_prefix}-{op_name}-{op_mode}it")
3055                if 'pre' in op[op_mode]:
3056                    members.append((cb_names[op_mode]['pre'], c_lower(op[op_mode]['pre'])))
3057                members.append((op_mode + 'it', name))
3058                if 'post' in op[op_mode]:
3059                    members.append((cb_names[op_mode]['post'], c_lower(op[op_mode]['post'])))
3060                if 'request' in op[op_mode]:
3061                    struct = Struct(family, op['attribute-set'],
3062                                    type_list=op[op_mode]['request']['attributes'])
3063
3064                    if op.dual_policy:
3065                        name = c_lower(f"{family.ident_name}-{op_name}-{op_mode}-nl-policy")
3066                    else:
3067                        name = c_lower(f"{family.ident_name}-{op_name}-nl-policy")
3068                    members.append(('policy', name))
3069                    members.append(('maxattr', struct.attr_max_val.enum_name))
3070                flags = (op['flags'] if 'flags' in op else []) + ['cmd-cap-' + op_mode]
3071                members.append(('flags', ' | '.join([c_upper('genl-' + x) for x in flags])))
3072                cw.write_struct_init(members)
3073                cw.block_end(line=',')
3074    cw.ifdef_block(None)
3075
3076    cw.block_end(line=';')
3077    cw.nl()
3078
3079
3080def print_kernel_mcgrp_hdr(family, cw):
3081    if not family.mcgrps['list']:
3082        return
3083
3084    cw.block_start('enum')
3085    for grp in family.mcgrps['list']:
3086        grp_id = c_upper(f"{family.ident_name}-nlgrp-{grp['name']},")
3087        cw.p(grp_id)
3088    cw.block_end(';')
3089    cw.nl()
3090
3091
3092def print_kernel_mcgrp_src(family, cw):
3093    if not family.mcgrps['list']:
3094        return
3095
3096    cw.block_start('static const struct genl_multicast_group ' + family.c_name + '_nl_mcgrps[] =')
3097    for grp in family.mcgrps['list']:
3098        name = grp['name']
3099        grp_id = c_upper(f"{family.ident_name}-nlgrp-{name}")
3100        cw.p('[' + grp_id + '] = { "' + name + '", },')
3101    cw.block_end(';')
3102    cw.nl()
3103
3104
3105def print_kernel_family_struct_hdr(family, cw):
3106    if not kernel_can_gen_family_struct(family):
3107        return
3108
3109    cw.p(f"extern struct genl_family {family.c_name}_nl_family;")
3110    cw.nl()
3111    if 'sock-priv' in family.kernel_family:
3112        cw.p(f'void {family.c_name}_nl_sock_priv_init({family.kernel_family["sock-priv"]} *priv);')
3113        cw.p(f'void {family.c_name}_nl_sock_priv_destroy({family.kernel_family["sock-priv"]} *priv);')
3114        cw.nl()
3115
3116
3117def print_kernel_family_struct_src(family, cw):
3118    if not kernel_can_gen_family_struct(family):
3119        return
3120
3121    if 'sock-priv' in family.kernel_family:
3122        # Generate "trampolines" to make CFI happy
3123        cw.write_func("static void", f"__{family.c_name}_nl_sock_priv_init",
3124                      [f"{family.c_name}_nl_sock_priv_init(priv);"],
3125                      ["void *priv"])
3126        cw.nl()
3127        cw.write_func("static void", f"__{family.c_name}_nl_sock_priv_destroy",
3128                      [f"{family.c_name}_nl_sock_priv_destroy(priv);"],
3129                      ["void *priv"])
3130        cw.nl()
3131
3132    cw.block_start(f"struct genl_family {family.ident_name}_nl_family __ro_after_init =")
3133    cw.p('.name\t\t= ' + family.fam_key + ',')
3134    cw.p('.version\t= ' + family.ver_key + ',')
3135    cw.p('.netnsok\t= true,')
3136    cw.p('.parallel_ops\t= true,')
3137    cw.p('.module\t\t= THIS_MODULE,')
3138    if family.kernel_policy == 'per-op':
3139        cw.p(f'.ops\t\t= {family.c_name}_nl_ops,')
3140        cw.p(f'.n_ops\t\t= ARRAY_SIZE({family.c_name}_nl_ops),')
3141    elif family.kernel_policy == 'split':
3142        cw.p(f'.split_ops\t= {family.c_name}_nl_ops,')
3143        cw.p(f'.n_split_ops\t= ARRAY_SIZE({family.c_name}_nl_ops),')
3144    if family.mcgrps['list']:
3145        cw.p(f'.mcgrps\t\t= {family.c_name}_nl_mcgrps,')
3146        cw.p(f'.n_mcgrps\t= ARRAY_SIZE({family.c_name}_nl_mcgrps),')
3147    if 'sock-priv' in family.kernel_family:
3148        cw.p(f'.sock_priv_size\t= sizeof({family.kernel_family["sock-priv"]}),')
3149        cw.p(f'.sock_priv_init\t= __{family.c_name}_nl_sock_priv_init,')
3150        cw.p(f'.sock_priv_destroy = __{family.c_name}_nl_sock_priv_destroy,')
3151    cw.block_end(';')
3152
3153
3154def uapi_enum_start(family, cw, obj, ckey='', enum_name='enum-name'):
3155    start_line = 'enum'
3156    if enum_name in obj:
3157        if obj[enum_name]:
3158            start_line = 'enum ' + c_lower(obj[enum_name])
3159    elif ckey and ckey in obj:
3160        start_line = 'enum ' + family.c_name + '_' + c_lower(obj[ckey])
3161    cw.block_start(line=start_line)
3162
3163
3164def render_uapi_unified(family, cw, max_by_define, separate_ntf):
3165    max_name = c_upper(family.get('cmd-max-name', f"{family.op_prefix}MAX"))
3166    cnt_name = c_upper(family.get('cmd-cnt-name', f"__{family.op_prefix}MAX"))
3167    max_value = f"({cnt_name} - 1)"
3168
3169    uapi_enum_start(family, cw, family['operations'], 'enum-name')
3170    val = 0
3171    for op in family.msgs.values():
3172        if separate_ntf and ('notify' in op or 'event' in op):
3173            continue
3174
3175        suffix = ','
3176        if op.value != val:
3177            suffix = f" = {op.value},"
3178            val = op.value
3179        cw.p(op.enum_name + suffix)
3180        val += 1
3181    cw.nl()
3182    cw.p(cnt_name + ('' if max_by_define else ','))
3183    if not max_by_define:
3184        cw.p(f"{max_name} = {max_value}")
3185    cw.block_end(line=';')
3186    if max_by_define:
3187        cw.p(f"#define {max_name} {max_value}")
3188    cw.nl()
3189
3190
3191def render_uapi_directional(family, cw, max_by_define):
3192    max_name = f"{family.op_prefix}USER_MAX"
3193    cnt_name = f"__{family.op_prefix}USER_CNT"
3194    max_value = f"({cnt_name} - 1)"
3195
3196    cw.block_start(line='enum')
3197    cw.p(c_upper(f'{family.name}_MSG_USER_NONE = 0,'))
3198    val = 0
3199    for op in family.msgs.values():
3200        if 'do' in op and 'event' not in op:
3201            suffix = ','
3202            if op.value and op.value != val:
3203                suffix = f" = {op.value},"
3204                val = op.value
3205            cw.p(op.enum_name + suffix)
3206            val += 1
3207    cw.nl()
3208    cw.p(cnt_name + ('' if max_by_define else ','))
3209    if not max_by_define:
3210        cw.p(f"{max_name} = {max_value}")
3211    cw.block_end(line=';')
3212    if max_by_define:
3213        cw.p(f"#define {max_name} {max_value}")
3214    cw.nl()
3215
3216    max_name = f"{family.op_prefix}KERNEL_MAX"
3217    cnt_name = f"__{family.op_prefix}KERNEL_CNT"
3218    max_value = f"({cnt_name} - 1)"
3219
3220    cw.block_start(line='enum')
3221    cw.p(c_upper(f'{family.name}_MSG_KERNEL_NONE = 0,'))
3222    val = 0
3223    for op in family.msgs.values():
3224        if ('do' in op and 'reply' in op['do']) or 'notify' in op or 'event' in op:
3225            enum_name = op.enum_name
3226            if 'event' not in op and 'notify' not in op:
3227                enum_name = f'{enum_name}_REPLY'
3228
3229            suffix = ','
3230            if op.value and op.value != val:
3231                suffix = f" = {op.value},"
3232                val = op.value
3233            cw.p(enum_name + suffix)
3234            val += 1
3235    cw.nl()
3236    cw.p(cnt_name + ('' if max_by_define else ','))
3237    if not max_by_define:
3238        cw.p(f"{max_name} = {max_value}")
3239    cw.block_end(line=';')
3240    if max_by_define:
3241        cw.p(f"#define {max_name} {max_value}")
3242    cw.nl()
3243
3244
3245def render_uapi(family, cw):
3246    hdr_prot = f"_UAPI_LINUX_{c_upper(family.uapi_header_name)}_H"
3247    hdr_prot = hdr_prot.replace('/', '_')
3248    cw.p('#ifndef ' + hdr_prot)
3249    cw.p('#define ' + hdr_prot)
3250    cw.nl()
3251
3252    defines = [(family.fam_key, family["name"]),
3253               (family.ver_key, family.get('version', 1))]
3254    cw.writes_defines(defines)
3255    cw.nl()
3256
3257    defines = []
3258    for const in family['definitions']:
3259        if const.get('header'):
3260            continue
3261        if const.get('scope', 'uapi') != 'uapi':
3262            continue
3263
3264        if const['type'] != 'const':
3265            cw.writes_defines(defines)
3266            defines = []
3267            cw.nl()
3268
3269        # Write kdoc for enum and flags (one day maybe also structs)
3270        if const['type'] == 'enum' or const['type'] == 'flags':
3271            enum = family.consts[const['name']]
3272
3273            if enum.header:
3274                continue
3275
3276            if enum.has_doc():
3277                if enum.has_entry_doc():
3278                    cw.p('/**')
3279                    doc = ''
3280                    if 'doc' in enum:
3281                        doc = ' - ' + enum['doc']
3282                    cw.write_doc_line(enum.enum_name + doc)
3283                else:
3284                    cw.p('/*')
3285                    cw.write_doc_line(enum['doc'], indent=False)
3286                for entry in enum.entries.values():
3287                    if entry.has_doc():
3288                        doc = '@' + entry.c_name + ': ' + entry['doc']
3289                        cw.write_doc_line(doc)
3290                cw.p(' */')
3291
3292            uapi_enum_start(family, cw, const, 'name')
3293            name_pfx = const.get('name-prefix', f"{family.ident_name}-{const['name']}-")
3294            for entry in enum.entries.values():
3295                suffix = ','
3296                if entry.value_change:
3297                    suffix = f" = {entry.user_value()}" + suffix
3298                cw.p(entry.c_name + suffix)
3299
3300            if const.get('render-max', False):
3301                cw.nl()
3302                cw.p('/* private: */')
3303                if const['type'] == 'flags':
3304                    max_name = c_upper(name_pfx + 'mask')
3305                    max_val = f' = {enum.get_mask()},'
3306                    cw.p(max_name + max_val)
3307                else:
3308                    cnt_name = enum.enum_cnt_name
3309                    max_name = c_upper(name_pfx + 'max')
3310                    if not cnt_name:
3311                        cnt_name = '__' + name_pfx + 'max'
3312                    cw.p(c_upper(cnt_name) + ',')
3313                    cw.p(max_name + ' = (' + c_upper(cnt_name) + ' - 1)')
3314            cw.block_end(line=';')
3315            cw.nl()
3316        elif const['type'] == 'const':
3317            name_pfx = const.get('name-prefix', f"{family.ident_name}-")
3318            defines.append([c_upper(family.get('c-define-name',
3319                                               f"{name_pfx}{const['name']}")),
3320                            const['value']])
3321
3322    if defines:
3323        cw.writes_defines(defines)
3324        cw.nl()
3325
3326    max_by_define = family.get('max-by-define', False)
3327
3328    for _, attr_set in family.attr_sets.items():
3329        if attr_set.subset_of:
3330            continue
3331
3332        max_value = f"({attr_set.cnt_name} - 1)"
3333
3334        val = 0
3335        uapi_enum_start(family, cw, attr_set.yaml, 'enum-name')
3336        for _, attr in attr_set.items():
3337            suffix = ','
3338            if attr.value != val:
3339                suffix = f" = {attr.value},"
3340                val = attr.value
3341            val += 1
3342            cw.p(attr.enum_name + suffix)
3343        if attr_set.items():
3344            cw.nl()
3345        cw.p(attr_set.cnt_name + ('' if max_by_define else ','))
3346        if not max_by_define:
3347            cw.p(f"{attr_set.max_name} = {max_value}")
3348        cw.block_end(line=';')
3349        if max_by_define:
3350            cw.p(f"#define {attr_set.max_name} {max_value}")
3351        cw.nl()
3352
3353    # Commands
3354    separate_ntf = 'async-prefix' in family['operations']
3355
3356    if family.msg_id_model == 'unified':
3357        render_uapi_unified(family, cw, max_by_define, separate_ntf)
3358    elif family.msg_id_model == 'directional':
3359        render_uapi_directional(family, cw, max_by_define)
3360    else:
3361        raise Exception(f'Unsupported message enum-model {family.msg_id_model}')
3362
3363    if separate_ntf:
3364        uapi_enum_start(family, cw, family['operations'], enum_name='async-enum')
3365        for op in family.msgs.values():
3366            if separate_ntf and not ('notify' in op or 'event' in op):
3367                continue
3368
3369            suffix = ','
3370            if 'value' in op:
3371                suffix = f" = {op['value']},"
3372            cw.p(op.enum_name + suffix)
3373        cw.block_end(line=';')
3374        cw.nl()
3375
3376    # Multicast
3377    defines = []
3378    for grp in family.mcgrps['list']:
3379        name = grp['name']
3380        defines.append([c_upper(grp.get('c-define-name', f"{family.ident_name}-mcgrp-{name}")),
3381                        f'{name}'])
3382    cw.nl()
3383    if defines:
3384        cw.writes_defines(defines)
3385        cw.nl()
3386
3387    cw.p(f'#endif /* {hdr_prot} */')
3388
3389
3390def render_scoped_consts(family, cw, scope):
3391    defines = []
3392    for const in family['definitions']:
3393        if const['type'] != 'const':
3394            continue
3395        if const.get('header'):
3396            continue
3397        if const.get('scope') != scope:
3398            continue
3399        name_pfx = const.get('name-prefix', f"{family.ident_name}-")
3400        defines.append([
3401            c_upper(family.get('c-define-name',
3402                               f"{name_pfx}{const['name']}")),
3403            const['value']])
3404    if defines:
3405        cw.writes_defines(defines)
3406        cw.nl()
3407
3408
3409def _render_user_ntf_entry(ri, op):
3410    if not ri.family.is_classic():
3411        ri.cw.block_start(line=f"[{op.enum_name}] = ")
3412    else:
3413        crud_op = ri.family.req_by_value[op.rsp_value]
3414        ri.cw.block_start(line=f"[{crud_op.enum_name}] = ")
3415    ri.cw.p(f".alloc_sz\t= sizeof({type_name(ri, 'event')}),")
3416    ri.cw.p(f".cb\t\t= {op_prefix(ri, 'reply', deref=True)}_parse,")
3417    ri.cw.p(f".policy\t\t= &{ri.struct['reply'].render_name}_nest,")
3418    ri.cw.p(f".free\t\t= (void *){op_prefix(ri, 'notify')}_free,")
3419    ri.cw.block_end(line=',')
3420
3421
3422def render_user_family(family, cw, prototype):
3423    symbol = f'const struct ynl_family ynl_{family.c_name}_family'
3424    if prototype:
3425        cw.p(f'extern {symbol};')
3426        return
3427
3428    if family.ntfs:
3429        cw.block_start(line=f"static const struct ynl_ntf_info {family.c_name}_ntf_info[] = ")
3430        for ntf_op_name, ntf_op in family.ntfs.items():
3431            if 'notify' in ntf_op:
3432                op = family.ops[ntf_op['notify']]
3433                ri = RenderInfo(cw, family, "user", op, "notify")
3434            elif 'event' in ntf_op:
3435                ri = RenderInfo(cw, family, "user", ntf_op, "event")
3436            else:
3437                raise Exception('Invalid notification ' + ntf_op_name)
3438            _render_user_ntf_entry(ri, ntf_op)
3439        for _op_name, op in family.ops.items():
3440            if 'event' not in op:
3441                continue
3442            ri = RenderInfo(cw, family, "user", op, "event")
3443            _render_user_ntf_entry(ri, op)
3444        cw.block_end(line=";")
3445        cw.nl()
3446
3447    cw.block_start(f'{symbol} = ')
3448    cw.p(f'.name\t\t= "{family.c_name}",')
3449    if family.is_classic():
3450        cw.p('.is_classic\t= true,')
3451        cw.p(f'.classic_id\t= {family.get("protonum")},')
3452    if family.is_classic():
3453        if family.fixed_header:
3454            cw.p(f'.hdr_len\t= sizeof(struct {c_lower(family.fixed_header)}),')
3455    elif family.fixed_header:
3456        cw.p(f'.hdr_len\t= sizeof(struct genlmsghdr) + sizeof(struct {c_lower(family.fixed_header)}),')
3457    else:
3458        cw.p('.hdr_len\t= sizeof(struct genlmsghdr),')
3459    if family.ntfs:
3460        cw.p(f".ntf_info\t= {family.c_name}_ntf_info,")
3461        cw.p(f".ntf_info_size\t= YNL_ARRAY_SIZE({family.c_name}_ntf_info),")
3462    cw.block_end(line=';')
3463
3464
3465def family_contains_bitfield32(family):
3466    for _, attr_set in family.attr_sets.items():
3467        if attr_set.subset_of:
3468            continue
3469        for _, attr in attr_set.items():
3470            if attr.type == "bitfield32":
3471                return True
3472    return False
3473
3474
3475def find_kernel_root(full_path):
3476    sub_path = ''
3477    while True:
3478        sub_path = os.path.join(os.path.basename(full_path), sub_path)
3479        full_path = os.path.dirname(full_path)
3480        maintainers = os.path.join(full_path, "MAINTAINERS")
3481        if os.path.exists(maintainers):
3482            return full_path, sub_path[:-1]
3483
3484
3485def main():
3486    parser = argparse.ArgumentParser(description='Netlink simple parsing generator')
3487    parser.add_argument('--mode', dest='mode', type=str, required=True,
3488                        choices=('user', 'kernel', 'uapi'))
3489    parser.add_argument('--spec', dest='spec', type=str, required=True)
3490    parser.add_argument('--header', dest='header', action='store_true', default=None)
3491    parser.add_argument('--source', dest='header', action='store_false')
3492    parser.add_argument('--user-header', nargs='+', default=[])
3493    parser.add_argument('--cmp-out', action='store_true', default=None,
3494                        help='Do not overwrite the output file if the new output is identical to the old')
3495    parser.add_argument('--exclude-op', action='append', default=[])
3496    parser.add_argument('-o', dest='out_file', type=str, default=None)
3497    parser.add_argument('--function-prefix', dest='fn_prefix', type=str)
3498    args = parser.parse_args()
3499
3500    if args.header is None:
3501        parser.error("--header or --source is required")
3502
3503    exclude_ops = [re.compile(expr) for expr in args.exclude_op]
3504
3505    try:
3506        parsed = Family(args.spec, exclude_ops, args.fn_prefix)
3507        if parsed.license != '((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)':
3508            print('Spec license:', parsed.license)
3509            print('License must be: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)')
3510            os.sys.exit(1)
3511    except pyyaml.YAMLError as exc:
3512        print(exc)
3513        os.sys.exit(1)
3514
3515    cw = CodeWriter(BaseNlLib(), args.out_file, overwrite=not args.cmp_out)
3516
3517    _, spec_kernel = find_kernel_root(args.spec)
3518    if args.mode == 'uapi' or args.header:
3519        cw.p(f'/* SPDX-License-Identifier: {parsed.license} */')
3520    else:
3521        cw.p(f'// SPDX-License-Identifier: {parsed.license}')
3522    cw.p("/* Do not edit directly, auto-generated from: */")
3523    cw.p(f"/*\t{spec_kernel} */")
3524    cw.p(f"/* YNL-GEN {args.mode} {'header' if args.header else 'source'} */")
3525    if args.exclude_op or args.user_header or args.fn_prefix:
3526        line = ''
3527        if args.user_header:
3528            line += ' --user-header '.join([''] + args.user_header)
3529        if args.exclude_op:
3530            line += ' --exclude-op '.join([''] + args.exclude_op)
3531        if args.fn_prefix:
3532            line += f' --function-prefix {args.fn_prefix}'
3533        cw.p(f'/* YNL-ARG{line} */')
3534    cw.p('/* To regenerate run: tools/net/ynl/ynl-regen.sh */')
3535    cw.nl()
3536
3537    if args.mode == 'uapi':
3538        render_uapi(parsed, cw)
3539        return
3540
3541    hdr_prot = f"_LINUX_{parsed.c_name.upper()}_GEN_H"
3542    if args.header:
3543        cw.p('#ifndef ' + hdr_prot)
3544        cw.p('#define ' + hdr_prot)
3545        cw.nl()
3546
3547    if args.out_file:
3548        hdr_file = os.path.basename(args.out_file[:-2]) + ".h"
3549    else:
3550        hdr_file = "generated_header_file.h"
3551
3552    if args.mode == 'kernel':
3553        cw.p('#include <net/netlink.h>')
3554        cw.p('#include <net/genetlink.h>')
3555        cw.nl()
3556        if not args.header:
3557            if args.out_file:
3558                cw.p(f'#include "{hdr_file}"')
3559            cw.nl()
3560        headers = ['uapi/' + parsed.uapi_header]
3561        headers += parsed.kernel_family.get('headers', [])
3562    else:
3563        cw.p('#include <stdlib.h>')
3564        cw.p('#include <string.h>')
3565        if args.header:
3566            cw.p('#include <linux/types.h>')
3567            if family_contains_bitfield32(parsed):
3568                cw.p('#include <linux/netlink.h>')
3569        else:
3570            cw.p(f'#include "{hdr_file}"')
3571            cw.p('#include "ynl.h"')
3572        headers = []
3573    for definition in parsed['definitions'] + parsed['attribute-sets']:
3574        if 'header' not in definition:
3575            continue
3576        scope = definition.get('scope', 'uapi')
3577        if scope != 'uapi' and scope != args.mode:
3578            continue
3579        headers.append(definition['header'])
3580    if args.mode == 'user':
3581        headers.append(parsed.uapi_header)
3582    seen_header = []
3583    for one in headers:
3584        if one not in seen_header:
3585            cw.p(f"#include <{one}>")
3586            seen_header.append(one)
3587    cw.nl()
3588
3589    if args.mode == "user":
3590        if not args.header:
3591            cw.p("#include <linux/genetlink.h>")
3592            cw.nl()
3593            for one in args.user_header:
3594                cw.p(f'#include "{one}"')
3595        else:
3596            render_scoped_consts(parsed, cw, 'user')
3597            cw.p('struct ynl_sock;')
3598            cw.nl()
3599            render_user_family(parsed, cw, True)
3600        cw.nl()
3601
3602    if args.mode == "kernel":
3603        if args.header:
3604            render_scoped_consts(parsed, cw, 'kernel')
3605            for _, struct in sorted(parsed.pure_nested_structs.items()):
3606                if struct.request:
3607                    cw.p('/* Common nested types */')
3608                    break
3609            for attr_set, struct in sorted(parsed.pure_nested_structs.items()):
3610                if struct.request:
3611                    print_req_policy_fwd(cw, struct)
3612            cw.nl()
3613
3614            if parsed.kernel_policy == 'global':
3615                cw.p(f"/* Global operation policy for {parsed.name} */")
3616
3617                struct = Struct(parsed, parsed.global_policy_set, type_list=parsed.global_policy)
3618                print_req_policy_fwd(cw, struct)
3619                cw.nl()
3620
3621            if parsed.kernel_policy in {'per-op', 'split'}:
3622                for _op_name, op in parsed.ops.items():
3623                    if 'do' in op and 'event' not in op:
3624                        ri = RenderInfo(cw, parsed, args.mode, op, "do")
3625                        print_req_policy_fwd(cw, ri.struct['request'], ri=ri)
3626                        cw.nl()
3627
3628            print_kernel_op_table_hdr(parsed, cw)
3629            print_kernel_mcgrp_hdr(parsed, cw)
3630            print_kernel_family_struct_hdr(parsed, cw)
3631        else:
3632            print_kernel_policy_ranges(parsed, cw)
3633            print_kernel_policy_sparse_enum_validates(parsed, cw)
3634
3635            for _, struct in sorted(parsed.pure_nested_structs.items()):
3636                if struct.request:
3637                    cw.p('/* Common nested types */')
3638                    break
3639            for attr_set, struct in sorted(parsed.pure_nested_structs.items()):
3640                if struct.request:
3641                    print_req_policy(cw, struct)
3642            cw.nl()
3643
3644            if parsed.kernel_policy == 'global':
3645                cw.p(f"/* Global operation policy for {parsed.name} */")
3646
3647                struct = Struct(parsed, parsed.global_policy_set, type_list=parsed.global_policy)
3648                print_req_policy(cw, struct)
3649                cw.nl()
3650
3651            for _op_name, op in parsed.ops.items():
3652                if parsed.kernel_policy in {'per-op', 'split'}:
3653                    for op_mode in ['do', 'dump']:
3654                        if op_mode in op and 'request' in op[op_mode]:
3655                            cw.p(f"/* {op.enum_name} - {op_mode} */")
3656                            ri = RenderInfo(cw, parsed, args.mode, op, op_mode)
3657                            print_req_policy(cw, ri.struct['request'], ri=ri)
3658                            cw.nl()
3659
3660            print_kernel_op_table(parsed, cw)
3661            print_kernel_mcgrp_src(parsed, cw)
3662            print_kernel_family_struct_src(parsed, cw)
3663
3664    if args.mode == "user":
3665        if args.header:
3666            cw.p('/* Enums */')
3667            put_op_name_fwd(parsed, cw)
3668
3669            for name, const in parsed.consts.items():
3670                if isinstance(const, EnumSet):
3671                    put_enum_to_str_fwd(parsed, cw, const)
3672            cw.nl()
3673
3674            cw.p('/* Common nested types */')
3675            for attr_set, struct in parsed.pure_nested_structs.items():
3676                ri = RenderInfo(cw, parsed, args.mode, "", "", attr_set)
3677                print_type_full(ri, struct)
3678
3679            for _op_name, op in parsed.ops.items():
3680                cw.p(f"/* ============== {op.enum_name} ============== */")
3681
3682                if 'do' in op and 'event' not in op:
3683                    cw.p(f"/* {op.enum_name} - do */")
3684                    ri = RenderInfo(cw, parsed, args.mode, op, "do")
3685                    print_req_type(ri)
3686                    print_req_type_helpers(ri)
3687                    cw.nl()
3688                    print_rsp_type(ri)
3689                    print_rsp_type_helpers(ri)
3690                    cw.nl()
3691                    print_req_prototype(ri)
3692                    cw.nl()
3693
3694                if 'dump' in op:
3695                    cw.p(f"/* {op.enum_name} - dump */")
3696                    ri = RenderInfo(cw, parsed, args.mode, op, 'dump')
3697                    print_req_type(ri)
3698                    print_req_type_helpers(ri)
3699                    if not ri.type_consistent or ri.type_oneside:
3700                        print_rsp_type(ri)
3701                    print_wrapped_type(ri)
3702                    print_dump_prototype(ri)
3703                    cw.nl()
3704
3705                if op.has_ntf:
3706                    cw.p(f"/* {op.enum_name} - notify */")
3707                    ri = RenderInfo(cw, parsed, args.mode, op, 'notify')
3708                    if not ri.type_consistent:
3709                        raise Exception(f'Only notifications with consistent types supported ({op.name})')
3710                    print_wrapped_type(ri)
3711
3712            for _op_name, op in parsed.ntfs.items():
3713                if 'event' in op:
3714                    ri = RenderInfo(cw, parsed, args.mode, op, 'event')
3715                    cw.p(f"/* {op.enum_name} - event */")
3716                    print_rsp_type(ri)
3717                    cw.nl()
3718                    print_wrapped_type(ri)
3719            cw.nl()
3720        else:
3721            cw.p('/* Enums */')
3722            put_op_name(parsed, cw)
3723
3724            for name, const in parsed.consts.items():
3725                if isinstance(const, EnumSet):
3726                    put_enum_to_str(parsed, cw, const)
3727            cw.nl()
3728
3729            has_recursive_nests = False
3730            cw.p('/* Policies */')
3731            for struct in parsed.pure_nested_structs.values():
3732                if struct.recursive:
3733                    put_typol_fwd(cw, struct)
3734                    has_recursive_nests = True
3735            if has_recursive_nests:
3736                cw.nl()
3737            for struct in parsed.pure_nested_structs.values():
3738                put_typol(cw, struct)
3739            for name in parsed.root_sets:
3740                struct = Struct(parsed, name)
3741                put_typol(cw, struct)
3742
3743            cw.p('/* Common nested types */')
3744            if has_recursive_nests:
3745                for attr_set, struct in parsed.pure_nested_structs.items():
3746                    ri = RenderInfo(cw, parsed, args.mode, "", "", attr_set)
3747                    free_rsp_nested_prototype(ri)
3748                    if struct.request:
3749                        put_req_nested_prototype(ri, struct)
3750                    if struct.reply:
3751                        parse_rsp_nested_prototype(ri, struct)
3752                cw.nl()
3753            for attr_set, struct in parsed.pure_nested_structs.items():
3754                ri = RenderInfo(cw, parsed, args.mode, "", "", attr_set)
3755
3756                free_rsp_nested(ri, struct)
3757                if struct.request:
3758                    put_req_nested(ri, struct)
3759                if struct.reply:
3760                    parse_rsp_nested(ri, struct)
3761
3762            for _op_name, op in parsed.ops.items():
3763                cw.p(f"/* ============== {op.enum_name} ============== */")
3764                if 'do' in op and 'event' not in op:
3765                    cw.p(f"/* {op.enum_name} - do */")
3766                    ri = RenderInfo(cw, parsed, args.mode, op, "do")
3767                    print_req_free(ri)
3768                    print_rsp_free(ri)
3769                    parse_rsp_msg(ri)
3770                    print_req(ri)
3771                    cw.nl()
3772
3773                if 'dump' in op:
3774                    cw.p(f"/* {op.enum_name} - dump */")
3775                    ri = RenderInfo(cw, parsed, args.mode, op, "dump")
3776                    if not ri.type_consistent or ri.type_oneside:
3777                        parse_rsp_msg(ri, deref=True)
3778                    print_req_free(ri)
3779                    print_dump_type_free(ri)
3780                    print_dump(ri)
3781                    cw.nl()
3782
3783                if op.has_ntf:
3784                    cw.p(f"/* {op.enum_name} - notify */")
3785                    ri = RenderInfo(cw, parsed, args.mode, op, 'notify')
3786                    if not ri.type_consistent:
3787                        raise Exception(f'Only notifications with consistent types supported ({op.name})')
3788                    print_ntf_type_free(ri)
3789
3790            for _op_name, op in parsed.ntfs.items():
3791                if 'event' in op:
3792                    cw.p(f"/* {op.enum_name} - event */")
3793
3794                    ri = RenderInfo(cw, parsed, args.mode, op, "do")
3795                    parse_rsp_msg(ri)
3796
3797                    ri = RenderInfo(cw, parsed, args.mode, op, "event")
3798                    print_ntf_type_free(ri)
3799            cw.nl()
3800            render_user_family(parsed, cw, False)
3801
3802    if args.header:
3803        cw.p(f'#endif /* {hdr_prot} */')
3804
3805
3806if __name__ == "__main__":
3807    main()
3808