-
Notifications
You must be signed in to change notification settings - Fork 0
/
ynl-gen-cpp.py
executable file
·2410 lines (1962 loc) · 75.7 KB
/
ynl-gen-cpp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import argparse
import collections
import filecmp
import os
import re
import shutil
import tempfile
import yaml
from lib import (
SpecAttr,
SpecAttrSet,
SpecEnumEntry,
SpecEnumSet,
SpecFamily,
SpecOperation,
)
def c_upper(name):
return name.upper().replace("-", "_")
def c_lower(name):
return name.lower().replace("-", "_")
def limit_to_number(name):
"""
Turn a string limit like u32-max or s64-min into its numerical value
"""
if name[0] == "u" and name.endswith("-min"):
return 0
width = int(name[1:-4])
if name[0] == "s":
width -= 1
value = (1 << width) - 1
if name[0] == "s" and name.endswith("-min"):
value = -value - 1
return value
class BaseNlLib:
def get_family_id(self):
return "((struct ynl_sock*)ys)->family_id"
class Type(SpecAttr):
def __init__(self, family, attr_set, attr, value):
super().__init__(family, attr_set, attr, value)
self.attr = attr
self.attr_set = attr_set
self.type = attr["type"]
self.checks = attr.get("checks", {})
self.request = False
self.reply = False
if "len" in attr:
self.len = attr["len"]
if "nested-attributes" in attr:
self.nested_attrs = attr["nested-attributes"]
if self.nested_attrs == family.name:
self.nested_render_name = c_lower(f"{family.name}")
else:
self.nested_render_name = c_lower(f"{family.name}_{self.nested_attrs}")
if self.nested_attrs in self.family.consts:
self.nested_struct_type = self.nested_render_name + "_t"
else:
self.nested_struct_type = self.nested_render_name
self.c_name = c_lower(self.name)
if self.c_name in _C_KW:
self.c_name += "_"
# Added by resolve():
self.enum_name = None
delattr(self, "enum_name")
def get_limit(self, limit, default=None):
value = self.checks.get(limit, default)
if value is None:
return value
elif value in self.family.consts:
return c_upper(f"{self.family['name']}-{value}")
if not isinstance(value, int):
value = limit_to_number(value)
return value
def resolve(self):
if "name-prefix" in self.attr:
enum_name = f"{self.attr['name-prefix']}{self.name}"
else:
enum_name = f"{self.attr_set.name_prefix}{self.name}"
self.enum_name = c_upper(enum_name)
def is_multi_val(self):
return None
def is_scalar(self):
return self.type in {"u8", "u16", "u32", "u64", "s32", "s64"}
def is_recursive(self):
return False
def is_recursive_for_op(self, ri):
return self.is_recursive() and not ri.op
def presence_type(self):
return "bit"
def presence_member(self, space, type_filter):
if self.presence_type() != type_filter:
return
if self.presence_type() == "bit":
pfx = "__" if space == "user" else ""
return f"{pfx}u32 {self.c_name}:1;"
if self.presence_type() == "len":
pfx = "__" if space == "user" else ""
return f"{pfx}u32 {self.c_name}_len;"
def _complex_member_type(self, ri):
return None
def arg_member(self, ri):
member = self._complex_member_type(ri)
if member:
arg = [member + " *" + self.c_name]
if self.presence_type() == "count":
arg += ["unsigned int n_" + self.c_name]
return arg
raise Exception(f"Struct member not implemented for class type {self.type}")
def struct_member(self, ri):
member = self._complex_member_type(ri)
if member:
vec = True if self.is_multi_val() else False
if self.is_recursive_for_op(ri):
vec = True
if vec:
ri.cw.p(f"std::vector<{member}> {self.c_name};")
else:
ri.cw.p(f"std::optional<{member}> {self.c_name};")
return
members = self.arg_member(ri)
for one in members:
ri.cw.p(one + ";")
def _attr_policy(self, policy):
return "{ .type = " + policy + ", }"
def attr_policy(self, cw):
policy = c_upper("nla-" + self.attr["type"])
spec = self._attr_policy(policy)
cw.p(f"\t[{self.enum_name}] = {spec},")
def _attr_typol(self):
raise Exception(f"Type policy not implemented for class type {self.type}")
def attr_typol(self, cw):
typol = self._attr_typol()
cw.p(f'arr[{self.enum_name}] = {"{"} .name = "{self.name}", {typol}{"}"};')
def _attr_put_line(self, ri, var, line):
if self.presence_type() == "flag":
ri.cw.p(f"if ({var}.{self.c_name})")
elif self.presence_type() == "bit":
member = self._complex_member_type(ri)
vec = True if self.is_multi_val() else False
if self.is_recursive_for_op(ri):
vec = True
if vec:
ri.cw.p(f"if ({var}.{self.c_name}.size() > 0)")
else:
ri.cw.p(f"if ({var}.{self.c_name}.has_value())")
elif self.presence_type() == "len":
ri.cw.p(f"if ({var}.{self.c_name}.size() > 0)")
ri.cw.p(f"{line};")
def _attr_put_simple(self, ri, var, put_type):
if self.presence_type() == "len":
line = f"ynl_attr_put_{put_type}(nlh, {self.enum_name}, {var}.{self.c_name}.data())"
else:
line = f"ynl_attr_put_{put_type}(nlh, {self.enum_name}, {var}.{self.c_name}.value())"
self._attr_put_line(ri, var, line)
def attr_put(self, ri, var):
raise Exception(f"Put not implemented for class type {self.type}")
def _attr_get(self, ri, var):
raise Exception(f"Attr get not implemented for class type {self.type}")
def attr_get(self, ri, var, first):
lines, init_lines, local_vars = self._attr_get(ri, var)
if type(lines) is str:
lines = [lines]
if type(init_lines) is str:
init_lines = [init_lines]
kw = "if" if first else "else if"
ri.cw.block_start(line=f"{kw} (type == {self.enum_name})")
if local_vars:
for local in local_vars:
ri.cw.p(local)
ri.cw.nl()
if not self.is_multi_val():
ri.cw.p("if (ynl_attr_validate(yarg, attr))")
ri.cw.p("return YNL_PARSE_CB_ERROR;")
if init_lines:
ri.cw.nl()
for line in init_lines:
ri.cw.p(line)
for line in lines:
ri.cw.p(line)
ri.cw.block_end()
return True
class TypeUnused(Type):
def presence_type(self):
return ""
def arg_member(self, ri):
return []
def _attr_get(self, ri, var):
return ["return YNL_PARSE_CB_ERROR;"], None, None
def _attr_typol(self):
return ".type = YNL_PT_REJECT, "
def attr_policy(self, cw):
pass
def attr_put(self, ri, var):
pass
def attr_get(self, ri, var, first):
pass
class TypePad(Type):
def presence_type(self):
return ""
def arg_member(self, ri):
return []
def _attr_typol(self):
return ".type = YNL_PT_IGNORE, "
def attr_put(self, ri, var):
pass
def attr_get(self, ri, var, first):
pass
def attr_policy(self, cw):
pass
class TypeScalar(Type):
def __init__(self, family, attr_set, attr, value):
super().__init__(family, attr_set, attr, value)
self.byte_order_comment = ""
if "byte-order" in attr:
self.byte_order_comment = f" /* {attr['byte-order']} */"
if "enum" in self.attr:
enum = self.family.consts[self.attr["enum"]]
low, high = enum.value_range()
if "min" not in self.checks:
if low != 0 or self.type[0] == "s":
self.checks["min"] = low
if "max" not in self.checks:
self.checks["max"] = high
if "min" in self.checks and "max" in self.checks:
if self.get_limit("min") > self.get_limit("max"):
raise Exception(
f'Invalid limit for "{self.name}" min: {self.get_limit("min")} max: {self.get_limit("max")}'
)
self.checks["range"] = True
low = min(self.get_limit("min", 0), self.get_limit("max", 0))
high = max(self.get_limit("min", 0), self.get_limit("max", 0))
if low < 0 and self.type[0] == "u":
raise Exception(
f'Invalid limit for "{self.name}" negative limit for unsigned type'
)
if low < -32768 or high > 32767:
self.checks["full-range"] = True
# Added by resolve():
self.is_bitfield = None
delattr(self, "is_bitfield")
self.type_name = None
delattr(self, "type_name")
def resolve(self):
self.resolve_up(super())
if "enum-as-flags" in self.attr and self.attr["enum-as-flags"]:
self.is_bitfield = True
elif "enum" in self.attr:
self.is_bitfield = self.family.consts[self.attr["enum"]]["type"] == "flags"
else:
self.is_bitfield = False
if not self.is_bitfield and "enum" in self.attr:
self.type_name = self.family.consts[self.attr["enum"]].user_type
elif self.is_auto_scalar:
self.type_name = "__" + self.type[0] + "64"
else:
self.type_name = "__" + self.type
def _attr_policy(self, policy):
if "flags-mask" in self.checks or self.is_bitfield:
if self.is_bitfield:
enum = self.family.consts[self.attr["enum"]]
mask = enum.get_mask(as_flags=True)
else:
flags = self.family.consts[self.checks["flags-mask"]]
flag_cnt = len(flags["entries"])
mask = (1 << flag_cnt) - 1
return f"NLA_POLICY_MASK({policy}, 0x{mask:x})"
elif "full-range" in self.checks:
return f"NLA_POLICY_FULL_RANGE({policy}, &{c_lower(self.enum_name)}_range)"
elif "range" in self.checks:
return f"NLA_POLICY_RANGE({policy}, {self.get_limit('min')}, {self.get_limit('max')})"
elif "min" in self.checks:
return f"NLA_POLICY_MIN({policy}, {self.get_limit('min')})"
elif "max" in self.checks:
return f"NLA_POLICY_MAX({policy}, {self.get_limit('max')})"
return super()._attr_policy(policy)
def _attr_typol(self):
return f".type = YNL_PT_U{c_upper(self.type[1:])}, "
def arg_member(self, ri):
return [
f"std::optional<{self.type_name}> {self.c_name}{self.byte_order_comment}"
]
def attr_put(self, ri, var):
self._attr_put_simple(ri, var, self.type)
def _attr_get(self, ri, var):
return (
f"{var}->{self.c_name} = ({self.type_name})ynl_attr_get_{self.type}(attr);",
None,
None,
)
def _setter_lines(self, ri, member, presence):
return [f"{member} = {self.c_name};"]
class TypeFlag(Type):
def arg_member(self, ri):
return [f"bool {self.c_name}"]
def presence_type(self):
return "flag"
def struct_member(self, ri):
ri.cw.p(f"bool {self.c_name}{{}};")
def _attr_typol(self):
return ".type = YNL_PT_FLAG, "
def attr_put(self, ri, var):
self._attr_put_line(ri, var, f"ynl_attr_put(nlh, {self.enum_name}, NULL, 0)")
def _attr_get(self, ri, var):
return [], None, None
def _setter_lines(self, ri, member, presence):
return []
class TypeString(Type):
def arg_member(self, ri):
return [f"std::string {self.c_name}"]
def presence_type(self):
return "len"
def struct_member(self, ri):
ri.cw.p(f"std::string {self.c_name};")
def _attr_typol(self):
return f".type = YNL_PT_NUL_STR, "
def _attr_policy(self, policy):
if "exact-len" in self.checks:
mem = "NLA_POLICY_EXACT_LEN(" + str(self.get_limit("exact-len")) + ")"
else:
mem = "{ .type = " + policy
if "max-len" in self.checks:
mem += ", .len = " + str(self.get_limit("max-len"))
mem += ", }"
return mem
def attr_policy(self, cw):
if self.checks.get("unterminated-ok", False):
policy = "NLA_STRING"
else:
policy = "NLA_NUL_STRING"
spec = self._attr_policy(policy)
cw.p(f"\t[{self.enum_name}] = {spec},")
def attr_put(self, ri, var):
self._attr_put_simple(ri, var, "str")
def _attr_get(self, ri, var):
return (
[
f"{var}->{self.c_name}.assign(ynl_attr_get_str(attr), ynl_attr_data_len(attr));",
],
None,
None,
)
def _setter_lines(self, ri, member, presence):
return [
f"{member} = {self.c_name};",
]
class TypeBinary(Type):
def arg_member(self, ri):
return [f"const void *{self.c_name}", "size_t len"]
def presence_type(self):
return "len"
def struct_member(self, ri):
ri.cw.p(f"std::vector<__u8> {self.c_name};")
def _attr_typol(self):
return f".type = YNL_PT_BINARY,"
def _attr_policy(self, policy):
if "exact-len" in self.checks:
mem = "NLA_POLICY_EXACT_LEN(" + str(self.get_limit("exact-len")) + ")"
else:
mem = "{ "
if len(self.checks) == 1 and "min-len" in self.checks:
mem += ".len = " + str(self.get_limit("min-len"))
elif len(self.checks) == 0:
mem += ".type = NLA_BINARY"
else:
raise Exception(
"One or more of binary type checks not implemented, yet"
)
mem += ", }"
return mem
def attr_put(self, ri, var):
self._attr_put_line(
ri,
var,
f"ynl_attr_put(nlh, {self.enum_name}, "
+ f"{var}.{self.c_name}.data(), {var}.{self.c_name}.size())",
)
def _attr_get(self, ri, var):
return (
[
f"unsigned int len = ynl_attr_data_len(attr);",
f"__u8 *data = (__u8*)ynl_attr_data(attr);",
f"{var}->{self.c_name}.assign(data, data + len);",
],
None,
None,
)
def _setter_lines(self, ri, member, presence):
return [
f"free({member});",
f"{presence}_len = len;",
f"{member} = malloc({presence}_len);",
f"memcpy({member}, {self.c_name}, {presence}_len);",
]
class TypeBitfield32(Type):
def _complex_member_type(self, ri):
return "struct nla_bitfield32"
def _attr_typol(self):
return f".type = YNL_PT_BITFIELD32, "
def _attr_policy(self, policy):
if not "enum" in self.attr:
raise Exception("Enum required for bitfield32 attr")
enum = self.family.consts[self.attr["enum"]]
mask = enum.get_mask(as_flags=True)
return f"NLA_POLICY_BITFIELD32({mask})"
def attr_put(self, ri, var):
line = f"ynl_attr_put(nlh, {self.enum_name}, &{var}->{self.c_name}, sizeof(struct nla_bitfield32))"
self._attr_put_line(ri, var, line)
def _attr_get(self, ri, var):
return (
f"memcpy(&{var}->{self.c_name}, ynl_attr_data(attr), sizeof(struct nla_bitfield32));",
None,
None,
)
def _setter_lines(self, ri, member, presence):
return [f"memcpy(&{member}, {self.c_name}, sizeof(struct nla_bitfield32));"]
class TypeNest(Type):
def is_recursive(self):
return self.family.pure_nested_structs[self.nested_attrs].recursive
def _complex_member_type(self, ri):
return self.nested_struct_type
def _attr_typol(self):
return f".type = YNL_PT_NEST, .nest = &{self.nested_render_name}_nest, "
def _attr_policy(self, policy):
return "NLA_POLICY_NESTED(" + self.nested_render_name + "_nl_policy)"
def attr_put(self, ri, var):
# at = "" if self.is_recursive_for_op(ri) else "&"
at = ""
self._attr_put_line(
ri,
var,
f"{self.nested_render_name}_put(nlh, "
+ f"{self.enum_name}, {at}{var}.{self.c_name}.value())",
)
def _attr_get(self, ri, var):
get_lines = [
f"if ({self.nested_render_name}_parse(&parg, attr))",
"return YNL_PARSE_CB_ERROR;",
]
init_lines = [
f"parg.rsp_policy = &{self.nested_render_name}_nest;",
f"parg.data = &{var}->{self.c_name};",
]
return get_lines, init_lines, None
class TypeMultiAttr(Type):
def __init__(self, family, attr_set, attr, value, base_type):
super().__init__(family, attr_set, attr, value)
self.base_type = base_type
def is_multi_val(self):
return True
def presence_type(self):
return "count"
def _complex_member_type(self, ri):
if "type" not in self.attr or self.attr["type"] == "nest":
return self.nested_struct_type
elif self.attr["type"] in scalars:
scalar_pfx = "__" if ri.ku_space == "user" else ""
return scalar_pfx + self.attr["type"]
else:
raise Exception(f"Sub-type {self.attr['type']} not supported yet")
def _attr_policy(self, policy):
return self.base_type._attr_policy(policy)
def _attr_typol(self):
return self.base_type._attr_typol()
def _attr_get(self, ri, var):
return f"n_{self.c_name}++;", None, None
def attr_put(self, ri, var):
if self.attr["type"] in scalars:
put_type = self.type
ri.cw.p(f"for (unsigned int i = 0; i < {var}.{self.c_name}.size(); i++)")
ri.cw.p(
f"ynl_attr_put_{put_type}(nlh, {self.enum_name}, {var}.{self.c_name}[i]);"
)
elif "type" not in self.attr or self.attr["type"] == "nest":
ri.cw.p(f"for (unsigned int i = 0; i < {var}.{self.c_name}.size(); i++)")
self._attr_put_line(
ri,
var,
f"{self.nested_render_name}_put(nlh, "
+ f"{self.enum_name}, {var}.{self.c_name}[i])",
)
else:
raise Exception(
f"Put of MultiAttr sub-type {self.attr['type']} not supported yet"
)
def _setter_lines(self, ri, member, presence):
# For multi-attr we have a count, not presence, hack up the presence
presence = (
presence[: -(len("_present.") + len(self.c_name))] + "n_" + self.c_name
)
return [
f"free({member});",
f"{member} = {self.c_name};",
f"{presence} = n_{self.c_name};",
]
class TypeArrayNest(Type):
def is_multi_val(self):
return True
def presence_type(self):
return "count"
def _complex_member_type(self, ri):
if "sub-type" not in self.attr or self.attr["sub-type"] == "nest":
return self.nested_struct_type
elif self.attr["sub-type"] in scalars:
scalar_pfx = "__" if ri.ku_space == "user" else ""
return scalar_pfx + self.attr["sub-type"]
else:
raise Exception(f"Sub-type {self.attr['sub-type']} not supported yet")
def _attr_typol(self):
return f".type = YNL_PT_NEST, .nest = &{self.nested_render_name}_nest, "
def _attr_get(self, ri, var):
local_vars = ["const struct nlattr *attr2;"]
get_lines = [
f"attr_{self.c_name} = attr;",
"ynl_attr_for_each_nested(attr2, attr)",
f"\t{var}->n_{self.c_name}++;",
]
return get_lines, None, local_vars
class TypeNestTypeValue(Type):
def _complex_member_type(self, ri):
return self.nested_struct_type
def _attr_typol(self):
return f".type = YNL_PT_NEST, .nest = &{self.nested_render_name}_nest, "
def _attr_get(self, ri, var):
prev = "attr"
tv_args = ""
get_lines = []
local_vars = []
init_lines = [
f"parg.rsp_policy = &{self.nested_render_name}_nest;",
f"parg.data = &{var}->{self.c_name};",
]
if "type-value" in self.attr:
tv_names = [c_lower(x) for x in self.attr["type-value"]]
local_vars += [f'const struct nlattr *attr_{", *attr_".join(tv_names)};']
local_vars += [f'__u32 {", ".join(tv_names)};']
for level in self.attr["type-value"]:
level = c_lower(level)
get_lines += [f"attr_{level} = ynl_attr_data({prev});"]
get_lines += [f"{level} = ynl_attr_type(attr_{level});"]
prev = "attr_" + level
tv_args = f", {', '.join(tv_names)}"
get_lines += [f"{self.nested_render_name}_parse(&parg, {prev}{tv_args});"]
return get_lines, init_lines, local_vars
class Struct:
def __init__(self, family, space_name, type_list=None, inherited=None):
self.family = family
self.space_name = space_name
self.attr_set = family.attr_sets[space_name]
# Use list to catch comparisons with empty sets
self._inherited = inherited if inherited is not None else []
self.inherited = []
self.nested = type_list is None
if family.name == c_lower(space_name):
self.render_name = c_lower(family.name)
else:
self.render_name = c_lower(family.name + "-" + space_name)
self.struct_name = self.render_name
if self.nested and space_name in family.consts:
self.struct_name += "_t"
self.ptr_name = self.render_name + "_t *"
self.ref_name = self.render_name + "_t& "
else:
self.ptr_name = self.render_name + " *"
self.ref_name = self.render_name + "& "
# All attr sets this one contains, directly or multiple levels down
self.child_nests = set()
self.request = False
self.reply = False
self.recursive = False
self.attr_list = []
self.attrs = dict()
if type_list is not None:
for t in type_list:
self.attr_list.append(
(t, self.attr_set[t]),
)
else:
for t in self.attr_set:
self.attr_list.append(
(t, self.attr_set[t]),
)
max_val = 0
self.attr_max_val = None
for name, attr in self.attr_list:
if attr.value >= max_val:
max_val = attr.value
self.attr_max_val = attr
self.attrs[name] = attr
def __iter__(self):
yield from self.attrs
def __getitem__(self, key):
return self.attrs[key]
def member_list(self):
return self.attr_list
def set_inherited(self, new_inherited):
if self._inherited != new_inherited:
raise Exception("Inheriting different members not supported")
self.inherited = [c_lower(x) for x in sorted(self._inherited)]
class EnumEntry(SpecEnumEntry):
def __init__(self, enum_set, yaml, prev, value_start):
super().__init__(enum_set, yaml, prev, value_start)
if prev:
self.value_change = self.value != prev.value + 1
else:
self.value_change = self.value != 0
self.value_change = self.value_change or self.enum_set["type"] == "flags"
# Added by resolve:
self.c_name = None
delattr(self, "c_name")
def resolve(self):
self.resolve_up(super())
self.c_name = c_upper(self.enum_set.value_pfx + self.name)
class EnumSet(SpecEnumSet):
def __init__(self, family, yaml):
self.render_name = c_lower(family.name + "-" + yaml["name"])
if "enum-name" in yaml:
if yaml["enum-name"]:
self.enum_name = c_lower(yaml["enum-name"])
self.user_type = self.enum_name
else:
self.enum_name = None
else:
self.enum_name = self.render_name
if self.enum_name:
self.user_type = self.enum_name
else:
self.user_type = "int"
self.value_pfx = yaml.get("name-prefix", f"{family.name}-{yaml['name']}-")
super().__init__(family, yaml)
def new_entry(self, entry, prev_entry, value_start):
return EnumEntry(self, entry, prev_entry, value_start)
def value_range(self):
low = min([x.value for x in self.entries.values()])
high = max([x.value for x in self.entries.values()])
if high - low + 1 != len(self.entries):
raise Exception("Can't get value range for a noncontiguous enum")
return low, high
class AttrSet(SpecAttrSet):
def __init__(self, family, yaml):
super().__init__(family, yaml)
if self.subset_of is None:
if "name-prefix" in yaml:
pfx = yaml["name-prefix"]
elif self.name == family.name:
pfx = family.name + "-a-"
else:
pfx = f"{family.name}-a-{self.name}-"
self.name_prefix = c_upper(pfx)
self.max_name = c_upper(
self.yaml.get("attr-max-name", f"{self.name_prefix}max")
)
self.cnt_name = c_upper(
self.yaml.get("attr-cnt-name", f"__{self.name_prefix}max")
)
else:
self.name_prefix = family.attr_sets[self.subset_of].name_prefix
self.max_name = family.attr_sets[self.subset_of].max_name
self.cnt_name = family.attr_sets[self.subset_of].cnt_name
# Added by resolve:
self.c_name = None
delattr(self, "c_name")
def resolve(self):
self.c_name = c_lower(self.name)
if self.c_name in _C_KW:
self.c_name += "_"
if self.c_name == self.family.c_name:
self.c_name = ""
def new_attr(self, elem, value):
if elem["type"] in scalars:
t = TypeScalar(self.family, self, elem, value)
elif elem["type"] == "unused":
t = TypeUnused(self.family, self, elem, value)
elif elem["type"] == "pad":
t = TypePad(self.family, self, elem, value)
elif elem["type"] == "flag":
t = TypeFlag(self.family, self, elem, value)
elif elem["type"] == "string":
t = TypeString(self.family, self, elem, value)
elif elem["type"] == "binary":
t = TypeBinary(self.family, self, elem, value)
elif elem["type"] == "bitfield32":
t = TypeBitfield32(self.family, self, elem, value)
elif elem["type"] == "nest":
t = TypeNest(self.family, self, elem, value)
elif elem["type"] == "indexed-array" and "sub-type" in elem:
if elem["sub-type"] == "nest":
t = TypeArrayNest(self.family, self, elem, value)
else:
raise Exception(f'new_attr: unsupported sub-type {elem["sub-type"]}')
elif elem["type"] == "nest-type-value":
t = TypeNestTypeValue(self.family, self, elem, value)
else:
raise Exception(f"No typed class for type {elem['type']}")
if "multi-attr" in elem and elem["multi-attr"]:
t = TypeMultiAttr(self.family, self, elem, value, t)
return t
class Operation(SpecOperation):
def __init__(self, family, yaml, req_value, rsp_value):
super().__init__(family, yaml, req_value, rsp_value)
self.render_name = c_lower(family.name + "_" + self.name)
self.dual_policy = ("do" in yaml and "request" in yaml["do"]) and (
"dump" in yaml and "request" in yaml["dump"]
)
self.has_ntf = False
# Added by resolve:
self.enum_name = None
delattr(self, "enum_name")
def resolve(self):
self.resolve_up(super())
if not self.is_async:
self.enum_name = self.family.op_prefix + c_upper(self.name)
else:
self.enum_name = self.family.async_op_prefix + c_upper(self.name)
def mark_has_ntf(self):
self.has_ntf = True
class Family(SpecFamily):
def __init__(self, file_name, exclude_ops):
# Added by resolve:
self.c_name = None
delattr(self, "c_name")
self.op_prefix = None
delattr(self, "op_prefix")
self.async_op_prefix = None
delattr(self, "async_op_prefix")
self.mcgrps = None
delattr(self, "mcgrps")
self.consts = None
delattr(self, "consts")
self.hooks = None
delattr(self, "hooks")
super().__init__(file_name, exclude_ops=exclude_ops)
self.fam_key = c_upper(
self.yaml.get("c-family-name", self.yaml["name"] + "_FAMILY_NAME")
)
self.ver_key = c_upper(
self.yaml.get("c-version-name", self.yaml["name"] + "_FAMILY_VERSION")
)
if "definitions" not in self.yaml:
self.yaml["definitions"] = []
if "uapi-header" in self.yaml:
self.uapi_header = self.yaml["uapi-header"]
else:
self.uapi_header = f"linux/{c_lower(self.name)}.h"
if self.uapi_header.startswith("linux/") and self.uapi_header.endswith(".h"):
self.uapi_header_name = self.uapi_header[6:-2]
else:
self.uapi_header_name = self.name
def resolve(self):
self.resolve_up(super())
if self.yaml.get("protocol", "genetlink") not in {
"genetlink",
"genetlink-c",
"genetlink-legacy",
}:
raise Exception("Codegen only supported for genetlink")
self.c_name = c_lower(self.name)
if "name-prefix" in self.yaml["operations"]:
self.op_prefix = c_upper(self.yaml["operations"]["name-prefix"])
else:
self.op_prefix = c_upper(self.yaml["name"] + "-cmd-")
if "async-prefix" in self.yaml["operations"]:
self.async_op_prefix = c_upper(self.yaml["operations"]["async-prefix"])
else:
self.async_op_prefix = self.op_prefix
self.mcgrps = self.yaml.get("mcast-groups", {"list": []})
self.hooks = dict()
for when in ["pre", "post"]:
self.hooks[when] = dict()
for op_mode in ["do", "dump"]:
self.hooks[when][op_mode] = dict()
self.hooks[when][op_mode]["set"] = set()
self.hooks[when][op_mode]["list"] = []
# dict space-name -> 'request': set(attrs), 'reply': set(attrs)
self.root_sets = dict()
# dict space-name -> set('request', 'reply')
self.pure_nested_structs = dict()
self._mark_notify()
self._mock_up_events()
self._load_root_sets()
self._load_nested_sets()
self._load_attr_use()
self._load_hooks()
self.kernel_policy = self.yaml.get("kernel-policy", "split")
if self.kernel_policy == "global":
self._load_global_policy()
def new_enum(self, elem):
return EnumSet(self, elem)
def new_attr_set(self, elem):
return AttrSet(self, elem)
def new_operation(self, elem, req_value, rsp_value):
return Operation(self, elem, req_value, rsp_value)
def _mark_notify(self):