|
13 | 13 | from typing import TYPE_CHECKING, Any, BinaryIO |
14 | 14 |
|
15 | 15 | from dissect.cstruct.bitbuffer import BitBuffer |
| 16 | +from dissect.cstruct.expression import Expression |
| 17 | +from dissect.cstruct.lexer import IDENTIFIER_TYPES |
16 | 18 | from dissect.cstruct.types.base import ( |
| 19 | + BaseArray, |
17 | 20 | BaseType, |
18 | 21 | MetaType, |
19 | 22 | _is_buffer_type, |
@@ -380,6 +383,102 @@ def commit(cls) -> None: |
380 | 383 | for key, value in classdict.items(): |
381 | 384 | setattr(cls, key, value) |
382 | 385 |
|
| 386 | + def cdef(cls, *, recursive: bool = False) -> str: |
| 387 | + """Render this structure (or union) back to its C-style definition. |
| 388 | +
|
| 389 | + When ``recursive=True``, any ``#define`` constants referenced in array sizes are emitted as well, so that the |
| 390 | + result can be parsed on its own. Note that the result is semantically equivalent to the original definition, |
| 391 | + but not necessarily identical. |
| 392 | +
|
| 393 | + Args: |
| 394 | + recursive: Also emit the definitions of any types referenced by this structure. |
| 395 | +
|
| 396 | + Returns: |
| 397 | + The C-style definition as a string. |
| 398 | + """ |
| 399 | + |
| 400 | + def _decompose(type_: MetaType) -> tuple[MetaType, int, list[int | Expression | None]]: |
| 401 | + dimensions = [] |
| 402 | + while issubclass(type_, BaseArray): |
| 403 | + dimensions.append(type_.num_entries) |
| 404 | + type_ = type_.type |
| 405 | + |
| 406 | + stars = 0 |
| 407 | + while issubclass(type_, Pointer): |
| 408 | + stars += 1 |
| 409 | + type_ = type_.type |
| 410 | + |
| 411 | + return type_, stars, dimensions |
| 412 | + |
| 413 | + def _deps(type_: StructureMetaType, seen: set[MetaType]) -> list[MetaType | str]: |
| 414 | + deps = [] |
| 415 | + for field in type_.__fields__: |
| 416 | + base, _, dimensions = _decompose(field.type) |
| 417 | + |
| 418 | + for dim in dimensions: |
| 419 | + if isinstance(dim, Expression): |
| 420 | + for token in dim._tokens: |
| 421 | + if ( |
| 422 | + token.type in IDENTIFIER_TYPES |
| 423 | + and token.value in cls.cs.consts |
| 424 | + and token.value not in seen |
| 425 | + ): |
| 426 | + deps.append(token.value) |
| 427 | + seen.add(token.value) |
| 428 | + |
| 429 | + if isinstance(base, StructureMetaType) and base not in seen: |
| 430 | + if base.__anonymous__: |
| 431 | + # Anonymous structures are not emitted, but their dependencies are |
| 432 | + deps.extend(_deps(base, seen)) |
| 433 | + else: |
| 434 | + seen.add(base) |
| 435 | + deps.extend(_deps(base, seen)) |
| 436 | + deps.append(base) |
| 437 | + |
| 438 | + elif isinstance(base, EnumMetaType) and base not in seen: |
| 439 | + seen.add(base) |
| 440 | + deps.append(base) |
| 441 | + |
| 442 | + return deps |
| 443 | + |
| 444 | + def _render_struct(type_: StructureMetaType, name: str) -> list[str]: |
| 445 | + keyword = "union" if isinstance(type_, UnionMetaType) else "struct" |
| 446 | + title = f"{keyword} {name}" if name else keyword |
| 447 | + |
| 448 | + lines = [f"{title} {{"] |
| 449 | + for field in type_.__fields__: |
| 450 | + base, stars, dimensions = _decompose(field.type) |
| 451 | + |
| 452 | + declarator = "*" * stars + (field.name or "") + "".join(f"[{dim or ''}]" for dim in dimensions) |
| 453 | + if field.bits is not None: |
| 454 | + declarator = f"{declarator} : {field.bits}" if declarator else f": {field.bits}" |
| 455 | + |
| 456 | + if isinstance(base, StructureMetaType) and base.__anonymous__: |
| 457 | + # Anonymous struct/union: inline the full definition |
| 458 | + lines.extend(f" {line}" for line in _render_struct(base, "")) |
| 459 | + lines[-1] = f"{lines[-1]} {declarator};" if declarator else f"{lines[-1]};" |
| 460 | + else: |
| 461 | + prefix = f"{base.__name__} " if declarator else base.__name__ |
| 462 | + lines.append(f" {prefix}{declarator};") |
| 463 | + |
| 464 | + lines.append("}") |
| 465 | + return lines |
| 466 | + |
| 467 | + deps = _deps(cls, {cls}) if recursive else [] |
| 468 | + deps.append(cls) |
| 469 | + |
| 470 | + consts = [] |
| 471 | + blocks = [] |
| 472 | + for type_ in deps: |
| 473 | + if isinstance(type_, str): |
| 474 | + consts.append(f"#define {type_} {cls.cs.consts[type_]!r}") |
| 475 | + elif isinstance(type_, EnumMetaType): |
| 476 | + blocks.append(type_.cdef()) |
| 477 | + else: |
| 478 | + blocks.append("\n".join(_render_struct(type_, type_.__name__)) + ";") |
| 479 | + |
| 480 | + return ("\n".join(consts) + "\n\n" if consts else "") + ("\n\n".join(blocks) if blocks else "") |
| 481 | + |
383 | 482 |
|
384 | 483 | class Structure(BaseType, metaclass=StructureMetaType): |
385 | 484 | """Base class for cstruct structure type classes. |
|
0 commit comments