nlspec.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. # SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
  2. import collections
  3. import importlib
  4. import os
  5. import yaml
  6. # To be loaded dynamically as needed
  7. jsonschema = None
  8. class SpecElement:
  9. """Netlink spec element.
  10. Abstract element of the Netlink spec. Implements the dictionary interface
  11. for access to the raw spec. Supports iterative resolution of dependencies
  12. across elements and class inheritance levels. The elements of the spec
  13. may refer to each other, and although loops should be very rare, having
  14. to maintain correct ordering of instantiation is painful, so the resolve()
  15. method should be used to perform parts of init which require access to
  16. other parts of the spec.
  17. Attributes:
  18. yaml raw spec as loaded from the spec file
  19. family back reference to the full family
  20. name name of the entity as listed in the spec (optional)
  21. ident_name name which can be safely used as identifier in code (optional)
  22. """
  23. def __init__(self, family, yaml):
  24. self.yaml = yaml
  25. self.family = family
  26. if 'name' in self.yaml:
  27. self.name = self.yaml['name']
  28. self.ident_name = self.name.replace('-', '_')
  29. self._super_resolved = False
  30. family.add_unresolved(self)
  31. def __getitem__(self, key):
  32. return self.yaml[key]
  33. def __contains__(self, key):
  34. return key in self.yaml
  35. def get(self, key, default=None):
  36. return self.yaml.get(key, default)
  37. def resolve_up(self, up):
  38. if not self._super_resolved:
  39. up.resolve()
  40. self._super_resolved = True
  41. def resolve(self):
  42. pass
  43. class SpecEnumEntry(SpecElement):
  44. """ Entry within an enum declared in the Netlink spec.
  45. Attributes:
  46. doc documentation string
  47. enum_set back reference to the enum
  48. value numerical value of this enum (use accessors in most situations!)
  49. Methods:
  50. raw_value raw value, i.e. the id in the enum, unlike user value which is a mask for flags
  51. user_value user value, same as raw value for enums, for flags it's the mask
  52. """
  53. def __init__(self, enum_set, yaml, prev, value_start):
  54. if isinstance(yaml, str):
  55. yaml = {'name': yaml}
  56. super().__init__(enum_set.family, yaml)
  57. self.doc = yaml.get('doc', '')
  58. self.enum_set = enum_set
  59. if 'value' in yaml:
  60. self.value = yaml['value']
  61. elif prev:
  62. self.value = prev.value + 1
  63. else:
  64. self.value = value_start
  65. def has_doc(self):
  66. return bool(self.doc)
  67. def raw_value(self):
  68. return self.value
  69. def user_value(self, as_flags=None):
  70. if self.enum_set['type'] == 'flags' or as_flags:
  71. return 1 << self.value
  72. else:
  73. return self.value
  74. class SpecEnumSet(SpecElement):
  75. """ Enum type
  76. Represents an enumeration (list of numerical constants)
  77. as declared in the "definitions" section of the spec.
  78. Attributes:
  79. type enum or flags
  80. entries entries by name
  81. entries_by_val entries by value
  82. Methods:
  83. get_mask for flags compute the mask of all defined values
  84. """
  85. def __init__(self, family, yaml):
  86. super().__init__(family, yaml)
  87. self.type = yaml['type']
  88. prev_entry = None
  89. value_start = self.yaml.get('value-start', 0)
  90. self.entries = dict()
  91. self.entries_by_val = dict()
  92. for entry in self.yaml['entries']:
  93. e = self.new_entry(entry, prev_entry, value_start)
  94. self.entries[e.name] = e
  95. self.entries_by_val[e.raw_value()] = e
  96. prev_entry = e
  97. def new_entry(self, entry, prev_entry, value_start):
  98. return SpecEnumEntry(self, entry, prev_entry, value_start)
  99. def has_doc(self):
  100. if 'doc' in self.yaml:
  101. return True
  102. for entry in self.entries.values():
  103. if entry.has_doc():
  104. return True
  105. return False
  106. def get_mask(self, as_flags=None):
  107. mask = 0
  108. for e in self.entries.values():
  109. mask += e.user_value(as_flags)
  110. return mask
  111. class SpecAttr(SpecElement):
  112. """ Single Netlink attribute type
  113. Represents a single attribute type within an attr space.
  114. Attributes:
  115. type string, attribute type
  116. value numerical ID when serialized
  117. attr_set Attribute Set containing this attr
  118. is_multi bool, attr may repeat multiple times
  119. struct_name string, name of struct definition
  120. sub_type string, name of sub type
  121. len integer, optional byte length of binary types
  122. display_hint string, hint to help choose format specifier
  123. when displaying the value
  124. sub_message string, name of sub message type
  125. selector string, name of attribute used to select
  126. sub-message type
  127. is_auto_scalar bool, attr is a variable-size scalar
  128. """
  129. def __init__(self, family, attr_set, yaml, value):
  130. super().__init__(family, yaml)
  131. self.type = yaml['type']
  132. self.value = value
  133. self.attr_set = attr_set
  134. self.is_multi = yaml.get('multi-attr', False)
  135. self.struct_name = yaml.get('struct')
  136. self.sub_type = yaml.get('sub-type')
  137. self.byte_order = yaml.get('byte-order')
  138. self.len = yaml.get('len')
  139. self.display_hint = yaml.get('display-hint')
  140. self.sub_message = yaml.get('sub-message')
  141. self.selector = yaml.get('selector')
  142. self.is_auto_scalar = self.type == "sint" or self.type == "uint"
  143. class SpecAttrSet(SpecElement):
  144. """ Netlink Attribute Set class.
  145. Represents a ID space of attributes within Netlink.
  146. Note that unlike other elements, which expose contents of the raw spec
  147. via the dictionary interface Attribute Set exposes attributes by name.
  148. Attributes:
  149. attrs ordered dict of all attributes (indexed by name)
  150. attrs_by_val ordered dict of all attributes (indexed by value)
  151. subset_of parent set if this is a subset, otherwise None
  152. """
  153. def __init__(self, family, yaml):
  154. super().__init__(family, yaml)
  155. self.subset_of = self.yaml.get('subset-of', None)
  156. self.attrs = collections.OrderedDict()
  157. self.attrs_by_val = collections.OrderedDict()
  158. if self.subset_of is None:
  159. val = 1
  160. for elem in self.yaml['attributes']:
  161. if 'value' in elem:
  162. val = elem['value']
  163. attr = self.new_attr(elem, val)
  164. self.attrs[attr.name] = attr
  165. self.attrs_by_val[attr.value] = attr
  166. val += 1
  167. else:
  168. real_set = family.attr_sets[self.subset_of]
  169. for elem in self.yaml['attributes']:
  170. attr = real_set[elem['name']]
  171. self.attrs[attr.name] = attr
  172. self.attrs_by_val[attr.value] = attr
  173. def new_attr(self, elem, value):
  174. return SpecAttr(self.family, self, elem, value)
  175. def __getitem__(self, key):
  176. return self.attrs[key]
  177. def __contains__(self, key):
  178. return key in self.attrs
  179. def __iter__(self):
  180. yield from self.attrs
  181. def items(self):
  182. return self.attrs.items()
  183. class SpecStructMember(SpecElement):
  184. """Struct member attribute
  185. Represents a single struct member attribute.
  186. Attributes:
  187. type string, type of the member attribute
  188. byte_order string or None for native byte order
  189. enum string, name of the enum definition
  190. len integer, optional byte length of binary types
  191. display_hint string, hint to help choose format specifier
  192. when displaying the value
  193. struct string, name of nested struct type
  194. """
  195. def __init__(self, family, yaml):
  196. super().__init__(family, yaml)
  197. self.type = yaml['type']
  198. self.byte_order = yaml.get('byte-order')
  199. self.enum = yaml.get('enum')
  200. self.len = yaml.get('len')
  201. self.display_hint = yaml.get('display-hint')
  202. self.struct = yaml.get('struct')
  203. class SpecStruct(SpecElement):
  204. """Netlink struct type
  205. Represents a C struct definition.
  206. Attributes:
  207. members ordered list of struct members
  208. """
  209. def __init__(self, family, yaml):
  210. super().__init__(family, yaml)
  211. self.members = []
  212. for member in yaml.get('members', []):
  213. self.members.append(self.new_member(family, member))
  214. def new_member(self, family, elem):
  215. return SpecStructMember(family, elem)
  216. def __iter__(self):
  217. yield from self.members
  218. def items(self):
  219. return self.members.items()
  220. class SpecSubMessage(SpecElement):
  221. """ Netlink sub-message definition
  222. Represents a set of sub-message formats for polymorphic nlattrs
  223. that contain type-specific sub messages.
  224. Attributes:
  225. name string, name of sub-message definition
  226. formats dict of sub-message formats indexed by match value
  227. """
  228. def __init__(self, family, yaml):
  229. super().__init__(family, yaml)
  230. self.formats = collections.OrderedDict()
  231. for elem in self.yaml['formats']:
  232. format = self.new_format(family, elem)
  233. self.formats[format.value] = format
  234. def new_format(self, family, format):
  235. return SpecSubMessageFormat(family, format)
  236. class SpecSubMessageFormat(SpecElement):
  237. """ Netlink sub-message format definition
  238. Represents a single format for a sub-message.
  239. Attributes:
  240. value attribute value to match against type selector
  241. fixed_header string, name of fixed header, or None
  242. attr_set string, name of attribute set, or None
  243. """
  244. def __init__(self, family, yaml):
  245. super().__init__(family, yaml)
  246. self.value = yaml.get('value')
  247. self.fixed_header = yaml.get('fixed-header')
  248. self.attr_set = yaml.get('attribute-set')
  249. class SpecOperation(SpecElement):
  250. """Netlink Operation
  251. Information about a single Netlink operation.
  252. Attributes:
  253. value numerical ID when serialized, None if req/rsp values differ
  254. req_value numerical ID when serialized, user -> kernel
  255. rsp_value numerical ID when serialized, user <- kernel
  256. modes supported operation modes (do, dump, event etc.)
  257. is_call bool, whether the operation is a call
  258. is_async bool, whether the operation is a notification
  259. is_resv bool, whether the operation does not exist (it's just a reserved ID)
  260. attr_set attribute set name
  261. fixed_header string, optional name of fixed header struct
  262. yaml raw spec as loaded from the spec file
  263. """
  264. def __init__(self, family, yaml, req_value, rsp_value):
  265. super().__init__(family, yaml)
  266. self.value = req_value if req_value == rsp_value else None
  267. self.req_value = req_value
  268. self.rsp_value = rsp_value
  269. self.modes = yaml.keys() & {'do', 'dump', 'event', 'notify'}
  270. self.is_call = 'do' in yaml or 'dump' in yaml
  271. self.is_async = 'notify' in yaml or 'event' in yaml
  272. self.is_resv = not self.is_async and not self.is_call
  273. self.fixed_header = self.yaml.get('fixed-header', family.fixed_header)
  274. # Added by resolve:
  275. self.attr_set = None
  276. delattr(self, "attr_set")
  277. def resolve(self):
  278. self.resolve_up(super())
  279. if 'attribute-set' in self.yaml:
  280. attr_set_name = self.yaml['attribute-set']
  281. elif 'notify' in self.yaml:
  282. msg = self.family.msgs[self.yaml['notify']]
  283. attr_set_name = msg['attribute-set']
  284. elif self.is_resv:
  285. attr_set_name = ''
  286. else:
  287. raise Exception(f"Can't resolve attribute set for op '{self.name}'")
  288. if attr_set_name:
  289. self.attr_set = self.family.attr_sets[attr_set_name]
  290. class SpecMcastGroup(SpecElement):
  291. """Netlink Multicast Group
  292. Information about a multicast group.
  293. Value is only used for classic netlink families that use the
  294. netlink-raw schema. Genetlink families use dynamic ID allocation
  295. where the ids of multicast groups get resolved at runtime. Value
  296. will be None for genetlink families.
  297. Attributes:
  298. name name of the mulitcast group
  299. value integer id of this multicast group for netlink-raw or None
  300. yaml raw spec as loaded from the spec file
  301. """
  302. def __init__(self, family, yaml):
  303. super().__init__(family, yaml)
  304. self.value = self.yaml.get('value')
  305. class SpecFamily(SpecElement):
  306. """ Netlink Family Spec class.
  307. Netlink family information loaded from a spec (e.g. in YAML).
  308. Takes care of unfolding implicit information which can be skipped
  309. in the spec itself for brevity.
  310. The class can be used like a dictionary to access the raw spec
  311. elements but that's usually a bad idea.
  312. Attributes:
  313. proto protocol type (e.g. genetlink)
  314. msg_id_model enum-model for operations (unified, directional etc.)
  315. license spec license (loaded from an SPDX tag on the spec)
  316. attr_sets dict of attribute sets
  317. msgs dict of all messages (index by name)
  318. sub_msgs dict of all sub messages (index by name)
  319. ops dict of all valid requests / responses
  320. ntfs dict of all async events
  321. consts dict of all constants/enums
  322. fixed_header string, optional name of family default fixed header struct
  323. mcast_groups dict of all multicast groups (index by name)
  324. kernel_family dict of kernel family attributes
  325. """
  326. def __init__(self, spec_path, schema_path=None, exclude_ops=None):
  327. with open(spec_path, "r") as stream:
  328. prefix = '# SPDX-License-Identifier: '
  329. first = stream.readline().strip()
  330. if not first.startswith(prefix):
  331. raise Exception('SPDX license tag required in the spec')
  332. self.license = first[len(prefix):]
  333. stream.seek(0)
  334. spec = yaml.safe_load(stream)
  335. self._resolution_list = []
  336. super().__init__(self, spec)
  337. self._exclude_ops = exclude_ops if exclude_ops else []
  338. self.proto = self.yaml.get('protocol', 'genetlink')
  339. self.msg_id_model = self.yaml['operations'].get('enum-model', 'unified')
  340. if schema_path is None:
  341. schema_path = os.path.dirname(os.path.dirname(spec_path)) + f'/{self.proto}.yaml'
  342. if schema_path:
  343. global jsonschema
  344. with open(schema_path, "r") as stream:
  345. schema = yaml.safe_load(stream)
  346. if jsonschema is None:
  347. jsonschema = importlib.import_module("jsonschema")
  348. jsonschema.validate(self.yaml, schema)
  349. self.attr_sets = collections.OrderedDict()
  350. self.sub_msgs = collections.OrderedDict()
  351. self.msgs = collections.OrderedDict()
  352. self.req_by_value = collections.OrderedDict()
  353. self.rsp_by_value = collections.OrderedDict()
  354. self.ops = collections.OrderedDict()
  355. self.ntfs = collections.OrderedDict()
  356. self.consts = collections.OrderedDict()
  357. self.mcast_groups = collections.OrderedDict()
  358. self.kernel_family = collections.OrderedDict(self.yaml.get('kernel-family', {}))
  359. last_exception = None
  360. while len(self._resolution_list) > 0:
  361. resolved = []
  362. unresolved = self._resolution_list
  363. self._resolution_list = []
  364. for elem in unresolved:
  365. try:
  366. elem.resolve()
  367. except (KeyError, AttributeError) as e:
  368. self._resolution_list.append(elem)
  369. last_exception = e
  370. continue
  371. resolved.append(elem)
  372. if len(resolved) == 0:
  373. raise last_exception
  374. def new_enum(self, elem):
  375. return SpecEnumSet(self, elem)
  376. def new_attr_set(self, elem):
  377. return SpecAttrSet(self, elem)
  378. def new_struct(self, elem):
  379. return SpecStruct(self, elem)
  380. def new_sub_message(self, elem):
  381. return SpecSubMessage(self, elem);
  382. def new_operation(self, elem, req_val, rsp_val):
  383. return SpecOperation(self, elem, req_val, rsp_val)
  384. def new_mcast_group(self, elem):
  385. return SpecMcastGroup(self, elem)
  386. def add_unresolved(self, elem):
  387. self._resolution_list.append(elem)
  388. def _dictify_ops_unified(self):
  389. self.fixed_header = self.yaml['operations'].get('fixed-header')
  390. val = 1
  391. for elem in self.yaml['operations']['list']:
  392. if 'value' in elem:
  393. val = elem['value']
  394. op = self.new_operation(elem, val, val)
  395. val += 1
  396. self.msgs[op.name] = op
  397. def _dictify_ops_directional(self):
  398. self.fixed_header = self.yaml['operations'].get('fixed-header')
  399. req_val = rsp_val = 1
  400. for elem in self.yaml['operations']['list']:
  401. if 'notify' in elem or 'event' in elem:
  402. if 'value' in elem:
  403. rsp_val = elem['value']
  404. req_val_next = req_val
  405. rsp_val_next = rsp_val + 1
  406. req_val = None
  407. elif 'do' in elem or 'dump' in elem:
  408. mode = elem['do'] if 'do' in elem else elem['dump']
  409. v = mode.get('request', {}).get('value', None)
  410. if v:
  411. req_val = v
  412. v = mode.get('reply', {}).get('value', None)
  413. if v:
  414. rsp_val = v
  415. rsp_inc = 1 if 'reply' in mode else 0
  416. req_val_next = req_val + 1
  417. rsp_val_next = rsp_val + rsp_inc
  418. else:
  419. raise Exception("Can't parse directional ops")
  420. if req_val == req_val_next:
  421. req_val = None
  422. if rsp_val == rsp_val_next:
  423. rsp_val = None
  424. skip = False
  425. for exclude in self._exclude_ops:
  426. skip |= bool(exclude.match(elem['name']))
  427. if not skip:
  428. op = self.new_operation(elem, req_val, rsp_val)
  429. req_val = req_val_next
  430. rsp_val = rsp_val_next
  431. self.msgs[op.name] = op
  432. def find_operation(self, name):
  433. """
  434. For a given operation name, find and return operation spec.
  435. """
  436. for op in self.yaml['operations']['list']:
  437. if name == op['name']:
  438. return op
  439. return None
  440. def resolve(self):
  441. self.resolve_up(super())
  442. definitions = self.yaml.get('definitions', [])
  443. for elem in definitions:
  444. if elem['type'] == 'enum' or elem['type'] == 'flags':
  445. self.consts[elem['name']] = self.new_enum(elem)
  446. elif elem['type'] == 'struct':
  447. self.consts[elem['name']] = self.new_struct(elem)
  448. else:
  449. self.consts[elem['name']] = elem
  450. for elem in self.yaml['attribute-sets']:
  451. attr_set = self.new_attr_set(elem)
  452. self.attr_sets[elem['name']] = attr_set
  453. for elem in self.yaml.get('sub-messages', []):
  454. sub_message = self.new_sub_message(elem)
  455. self.sub_msgs[sub_message.name] = sub_message
  456. if self.msg_id_model == 'unified':
  457. self._dictify_ops_unified()
  458. elif self.msg_id_model == 'directional':
  459. self._dictify_ops_directional()
  460. for op in self.msgs.values():
  461. if op.req_value is not None:
  462. self.req_by_value[op.req_value] = op
  463. if op.rsp_value is not None:
  464. self.rsp_by_value[op.rsp_value] = op
  465. if not op.is_async and 'attribute-set' in op:
  466. self.ops[op.name] = op
  467. elif op.is_async:
  468. self.ntfs[op.name] = op
  469. mcgs = self.yaml.get('mcast-groups')
  470. if mcgs:
  471. for elem in mcgs['list']:
  472. mcg = self.new_mcast_group(elem)
  473. self.mcast_groups[elem['name']] = mcg