romfs 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
romfs/__init__.py ADDED
@@ -0,0 +1,30 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2026 Junbo Zheng
3
+ """romfs: pure-Python reader and writer for Linux romfs (-rom1fs-) images."""
4
+
5
+ from .errors import (
6
+ BadMagicError,
7
+ ChecksumMismatchError,
8
+ RomFSError,
9
+ TruncatedImageError,
10
+ UnsupportedTypeError,
11
+ )
12
+ from .format import EntryType
13
+ from .nodes import RomFSNode
14
+ from .reader import RomFSReader
15
+ from .writer import RomFSWriter
16
+
17
+ __version__ = "0.0.1"
18
+
19
+ __all__ = [
20
+ "RomFSReader",
21
+ "RomFSWriter",
22
+ "RomFSNode",
23
+ "EntryType",
24
+ "RomFSError",
25
+ "BadMagicError",
26
+ "ChecksumMismatchError",
27
+ "TruncatedImageError",
28
+ "UnsupportedTypeError",
29
+ "__version__",
30
+ ]
romfs/cli.py ADDED
@@ -0,0 +1,145 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2026 Junbo Zheng
3
+ """Command-line interface for the romfs package."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import argparse
8
+ import sys
9
+ from importlib.metadata import PackageNotFoundError, version
10
+ from pathlib import Path
11
+
12
+ from .errors import RomFSError
13
+ from .format import EntryType
14
+ from .nodes import RomFSNode
15
+ from .reader import RomFSReader
16
+ from .writer import RomFSWriter
17
+
18
+ _TYPE_LABEL = {
19
+ EntryType.REGULAR: "f",
20
+ EntryType.DIRECTORY: "d",
21
+ EntryType.SYMLINK: "l",
22
+ }
23
+
24
+
25
+ def _version() -> str:
26
+ try:
27
+ return version("romfs")
28
+ except PackageNotFoundError:
29
+ from . import __version__
30
+
31
+ return __version__
32
+
33
+
34
+ def main(argv: list[str] | None = None) -> int:
35
+ p = argparse.ArgumentParser(
36
+ prog="romfs",
37
+ description=f"romfs {_version()} — read and write Linux romfs images.",
38
+ )
39
+ p.add_argument("-V", "--version", action="version", version=f"romfs {_version()}")
40
+ sub = p.add_subparsers(dest="cmd", required=True)
41
+
42
+ p_list = sub.add_parser("list", help="list the file tree in an image")
43
+ p_list.add_argument("image")
44
+
45
+ p_extract = sub.add_parser("extract", help="extract files from an image")
46
+ p_extract.add_argument("image")
47
+ p_extract.add_argument(
48
+ "path", nargs="?", help="extract a single entry to stdout (else all)"
49
+ )
50
+ p_extract.add_argument(
51
+ "-o", "--outdir", help="output directory for full extraction"
52
+ )
53
+
54
+ p_pack = sub.add_parser("pack", help="build an image from a directory tree")
55
+ p_pack.add_argument("srcdir")
56
+ p_pack.add_argument("-o", "--out", required=True, help="output image path")
57
+ p_pack.add_argument("-n", "--name", default="", help="volume name")
58
+
59
+ p_info = sub.add_parser("info", help="print image header info")
60
+ p_info.add_argument("image")
61
+ p_info.add_argument(
62
+ "--verify", action="store_true", help="verify the superblock checksum"
63
+ )
64
+
65
+ args = p.parse_args(argv)
66
+
67
+ try:
68
+ if args.cmd == "list":
69
+ return _cmd_list(args)
70
+ if args.cmd == "extract":
71
+ return _cmd_extract(args)
72
+ if args.cmd == "pack":
73
+ return _cmd_pack(args)
74
+ if args.cmd == "info":
75
+ return _cmd_info(args)
76
+ except RomFSError as e:
77
+ print(f"romfs: error: {e}", file=sys.stderr)
78
+ return 1
79
+ except FileNotFoundError as e:
80
+ print(f"romfs: error: {e}", file=sys.stderr)
81
+ return 1
82
+
83
+ return 0
84
+
85
+
86
+ def _cmd_list(args: argparse.Namespace) -> int:
87
+ with RomFSReader(args.image) as r:
88
+ for path, node in r.walk():
89
+ label = _TYPE_LABEL.get(node.type, "?")
90
+ print(f"{label} {node.size:>10} {path}")
91
+ return 0
92
+
93
+
94
+ def _cmd_extract(args: argparse.Namespace) -> int:
95
+ with RomFSReader(args.image) as r:
96
+ if args.path:
97
+ node = _find(r, args.path)
98
+ if node is None:
99
+ print(f"romfs: error: path not found: {args.path}", file=sys.stderr)
100
+ return 1
101
+ if node.type is EntryType.DIRECTORY:
102
+ print(
103
+ f"romfs: error: cannot extract a directory: {args.path}",
104
+ file=sys.stderr,
105
+ )
106
+ return 1
107
+ sys.stdout.buffer.write(r.read(node))
108
+ return 0
109
+ outdir = args.outdir or Path(args.image).stem + ".extracted"
110
+ r.extract(outdir)
111
+ print(f"extracted to {outdir}")
112
+ return 0
113
+
114
+
115
+ def _cmd_pack(args: argparse.Namespace) -> int:
116
+ RomFSWriter.from_directory(args.srcdir, volume_name=args.name).write(args.out)
117
+ print(f"packed {args.srcdir} -> {args.out}")
118
+ return 0
119
+
120
+
121
+ def _cmd_info(args: argparse.Namespace) -> int:
122
+ with RomFSReader(args.image, verify=args.verify) as r:
123
+ print(f"image: {args.image}")
124
+ print("magic: -rom1fs-")
125
+ print(f"full_size: {r.full_size} bytes")
126
+ print(f"volume: {r.volume_name!r}")
127
+ n_files = sum(1 for _, n in r.walk() if n.type is EntryType.REGULAR)
128
+ n_dirs = sum(1 for _, n in r.walk() if n.type is EntryType.DIRECTORY)
129
+ n_links = sum(1 for _, n in r.walk() if n.type is EntryType.SYMLINK)
130
+ print(f"entries: {n_files} file, {n_dirs} dir, {n_links} symlink")
131
+ if args.verify:
132
+ print("checksum: OK")
133
+ return 0
134
+
135
+
136
+ def _find(reader: RomFSReader, path: str) -> RomFSNode | None:
137
+ path = path.lstrip("/")
138
+ for p, node in reader.walk():
139
+ if p == path:
140
+ return node
141
+ return None
142
+
143
+
144
+ if __name__ == "__main__":
145
+ raise SystemExit(main())
romfs/errors.py ADDED
@@ -0,0 +1,34 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2026 Junbo Zheng
3
+ """romfs exception hierarchy."""
4
+
5
+ from __future__ import annotations
6
+
7
+
8
+ class RomFSError(Exception):
9
+ """Base class for all romfs errors."""
10
+
11
+
12
+ class BadMagicError(RomFSError):
13
+ """The image does not start with the ``-rom1fs-`` magic."""
14
+
15
+
16
+ class TruncatedImageError(RomFSError):
17
+ """The image is shorter than the bytes a header claims to occupy."""
18
+
19
+
20
+ class UnsupportedTypeError(RomFSError):
21
+ """The image contains an entry type this library does not handle."""
22
+
23
+
24
+ class ChecksumMismatchError(RomFSError):
25
+ """The superblock checksum region does not sum to zero."""
26
+
27
+
28
+ __all__ = [
29
+ "RomFSError",
30
+ "BadMagicError",
31
+ "TruncatedImageError",
32
+ "UnsupportedTypeError",
33
+ "ChecksumMismatchError",
34
+ ]
romfs/format.py ADDED
@@ -0,0 +1,175 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2026 Junbo Zheng
3
+ """romfs on-disk format primitives.
4
+
5
+ Byte-exact per the Linux kernel sources:
6
+ - fs/romfs/super.c (superblock parse, root offset, checksum)
7
+ - include/uapi/linux/romfs_fs.h (struct + constant definitions)
8
+ - Documentation/filesystems/romfs.rst
9
+
10
+ All multi-byte integers are big-endian. Every header and payload begins on a
11
+ 16-byte boundary. The superblock checksum covers the first
12
+ ``min(full_size, 512)`` bytes; the file-header checksum covers the whole header
13
+ (fixed 16 bytes + padded name). Both are stored as the two's complement of the
14
+ sum of the remaining words so that summing every word in the covered region
15
+ (including the checksum word) yields zero.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import struct
21
+ from enum import IntEnum
22
+
23
+ # --- Superblock ------------------------------------------------------------
24
+
25
+ # "-rom1fs-" as two big-endian words: '-','r','o','m' and '1','f','s','-'.
26
+ ROMFS_MAGIC_WORD0 = b"-rom"
27
+ ROMFS_MAGIC_WORD1 = b"1fs-"
28
+ ROMFS_MAGIC = ROMFS_MAGIC_WORD0 + ROMFS_MAGIC_WORD1 # b"-rom1fs-"
29
+
30
+ # The superblock checksum window: the first min(full_size, 512) bytes.
31
+ ROMFS_SUPERBLOCK_CHECK_WINDOW = 512
32
+
33
+ # Whole-image padding to a 1024-byte boundary (block-device mount requirement,
34
+ # per Documentation/filesystems/romfs.rst).
35
+ ROMFS_IMAGE_ALIGN = 1024
36
+
37
+ # --- File header -----------------------------------------------------------
38
+
39
+ ROMFH_SIZE = 16 # fixed part of a file header (next, spec, size, checksum)
40
+ ROMFH_PAD = 15 # low 4 bits carry type + exec, so offsets are 16-aligned
41
+ ROMFH_MASK = ~ROMFH_PAD & 0xFFFFFFFF # next/spec offset mask (clear low 4 bits)
42
+ ROMFH_TYPE = 7 # low 3 bits: entry type
43
+ ROMFH_EXEC = 8 # bit 3: executable
44
+
45
+ # 16-byte alignment for every header and payload.
46
+ ALIGN = 16
47
+
48
+
49
+ class EntryType(IntEnum):
50
+ """romfs entry type codes (low 3 bits of the ``next`` field)."""
51
+
52
+ HARDLINK = 0
53
+ DIRECTORY = 1
54
+ REGULAR = 2
55
+ SYMLINK = 3
56
+ BLOCKDEV = 4
57
+ CHARDEV = 5
58
+ SOCKET = 6
59
+ FIFO = 7
60
+
61
+
62
+ # --- Structs ---------------------------------------------------------------
63
+
64
+ # Superblock fixed part: magic0, magic1, full_size, checksum (name[] follows).
65
+ _superblock_head = struct.Struct(">4s4sII")
66
+ # File header fixed part: next, spec, size, checksum (name[] follows).
67
+ _file_head = struct.Struct(">IIII")
68
+
69
+
70
+ def align_up(n: int, alignment: int = ALIGN) -> int:
71
+ """Round ``n`` up to the next multiple of ``alignment``."""
72
+ return (n + alignment - 1) & ~(alignment - 1)
73
+
74
+
75
+ def align16(n: int) -> int:
76
+ """Round ``n`` up to the next 16-byte boundary."""
77
+ return align_up(n, ALIGN)
78
+
79
+
80
+ def name_field_size(name_len: int) -> int:
81
+ """Padded size of a null-terminated name field of ``name_len`` bytes.
82
+
83
+ The name is stored null-terminated and the whole field (name + NUL +
84
+ padding) is rounded up to 16 bytes. Minimum field size is 16.
85
+ """
86
+ return align16(name_len + 1)
87
+
88
+
89
+ def header_meta_size(name_len: int) -> int:
90
+ """Total metadata size of a file header: fixed 16 bytes + padded name."""
91
+ return ROMFH_SIZE + name_field_size(name_len)
92
+
93
+
94
+ def _sum_words(buf: bytes) -> int:
95
+ """Sum every big-endian uint32 word in ``buf`` (length must be a multiple of 4)."""
96
+ if len(buf) % 4 != 0:
97
+ raise ValueError(f"buffer length {len(buf)} is not a multiple of 4")
98
+ total = 0
99
+ for i in range(0, len(buf), 4):
100
+ total += struct.unpack_from(">I", buf, i)[0]
101
+ return total & 0xFFFFFFFF
102
+
103
+
104
+ def superblock_checksum(first_block: bytes) -> int:
105
+ """Compute the superblock checksum word for ``first_block``.
106
+
107
+ ``first_block`` is the first ``min(full_size, 512)`` bytes of the image
108
+ with the checksum field (offset 12) set to 0. The returned value, when
109
+ stored at offset 12, makes the sum of every word in ``first_block`` equal
110
+ to zero.
111
+ """
112
+ return (-_sum_words(first_block)) & 0xFFFFFFFF
113
+
114
+
115
+ def header_checksum(header: bytes) -> int:
116
+ """Compute the file-header checksum word for ``header``.
117
+
118
+ ``header`` is the full header (16 fixed bytes + padded name) with the
119
+ checksum field (offset 12) set to 0. Same convention as the superblock:
120
+ the stored value makes the whole header sum to zero.
121
+ """
122
+ return (-_sum_words(header)) & 0xFFFFFFFF
123
+
124
+
125
+ def verify_superblock_checksum(first_block: bytes, stored: int) -> bool:
126
+ """Return True if the superblock checksum region sums to zero."""
127
+ return (_sum_words(first_block[:ROMFS_SUPERBLOCK_CHECK_WINDOW]) & 0xFFFFFFFF) == 0
128
+
129
+
130
+ # --- Pack / unpack helpers -------------------------------------------------
131
+
132
+
133
+ def pack_superblock_head(full_size: int, checksum: int) -> bytes:
134
+ """Pack the 16-byte superblock fixed head (magic + size + checksum)."""
135
+ return _superblock_head.pack(
136
+ ROMFS_MAGIC_WORD0, ROMFS_MAGIC_WORD1, full_size, checksum
137
+ )
138
+
139
+
140
+ def unpack_superblock_head(buf: bytes) -> tuple[bytes, bytes, int, int]:
141
+ """Unpack the 16-byte superblock fixed head.
142
+
143
+ Returns ``(magic0, magic1, full_size, checksum)``.
144
+ """
145
+ return _superblock_head.unpack(buf[:ROMFH_SIZE])
146
+
147
+
148
+ def pack_file_head(next_off: int, spec: int, size: int, checksum: int) -> bytes:
149
+ """Pack the 16-byte file header fixed part."""
150
+ return _file_head.pack(
151
+ next_off & 0xFFFFFFFF,
152
+ spec & 0xFFFFFFFF,
153
+ size & 0xFFFFFFFF,
154
+ checksum & 0xFFFFFFFF,
155
+ )
156
+
157
+
158
+ def unpack_file_head(buf: bytes) -> tuple[int, int, int, int]:
159
+ """Unpack the 16-byte file header fixed part -> (next, spec, size, checksum)."""
160
+ return _file_head.unpack(buf[:ROMFH_SIZE])
161
+
162
+
163
+ def encode_name(name: str) -> bytes:
164
+ """Encode a name to its null-terminated, 16-byte-padded field bytes."""
165
+ raw = name.encode("utf-8")
166
+ field = name_field_size(len(raw))
167
+ return raw + b"\x00" * (field - len(raw))
168
+
169
+
170
+ def decode_name(field: bytes) -> str:
171
+ """Decode a padded name field up to its NUL terminator."""
172
+ nul = field.find(b"\x00")
173
+ if nul >= 0:
174
+ field = field[:nul]
175
+ return field.decode("utf-8")
romfs/nodes.py ADDED
@@ -0,0 +1,63 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2026 Junbo Zheng
3
+ """In-memory node tree shared by reader and writer."""
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Iterator
8
+ from dataclasses import dataclass, field
9
+ from typing import TYPE_CHECKING
10
+
11
+ from .format import EntryType
12
+
13
+ if TYPE_CHECKING:
14
+ from .reader import RomFSReader
15
+
16
+
17
+ @dataclass
18
+ class RomFSNode:
19
+ """A single romfs entry (regular file, directory, or symlink).
20
+
21
+ Reader and writer share this representation:
22
+ - ``data_offset``: absolute byte offset of the payload in the image
23
+ (regular/symlink). ``None`` until laid out / parsed.
24
+ - ``header_offset``: absolute byte offset of this entry's header.
25
+ - ``children`` / ``parent``: tree links (directories carry children).
26
+ - ``src_path``: writer-side source path to copy payload from.
27
+ - ``_reader``: reader-side back-reference for lazy content reads.
28
+ """
29
+
30
+ name: str
31
+ type: EntryType
32
+ size: int = 0
33
+ spec_info: int = 0
34
+ header_offset: int | None = None
35
+ data_offset: int | None = None
36
+ children: list[RomFSNode] = field(default_factory=list)
37
+ parent: RomFSNode | None = None
38
+ src_path: str | None = None
39
+ _reader: RomFSReader | None = field(default=None, repr=False)
40
+ # symlink target string (writer-side convenience; reader fills it on demand)
41
+ target: str | None = None
42
+
43
+ @property
44
+ def is_dir(self) -> bool:
45
+ return self.type is EntryType.DIRECTORY
46
+
47
+ @property
48
+ def is_regular(self) -> bool:
49
+ return self.type is EntryType.REGULAR
50
+
51
+ @property
52
+ def is_symlink(self) -> bool:
53
+ return self.type is EntryType.SYMLINK
54
+
55
+ def walk(self, prefix: str = "") -> Iterator[tuple[str, RomFSNode]]:
56
+ """Yield ``(path, node)`` for this node and all descendants (pre-order)."""
57
+ path = f"{prefix}/{self.name}" if prefix else self.name
58
+ yield path, self
59
+ for child in self.children:
60
+ yield from child.walk(path)
61
+
62
+
63
+ __all__ = ["RomFSNode"]
romfs/reader.py ADDED
@@ -0,0 +1,225 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2026 Junbo Zheng
3
+ """Parse a romfs image into a node tree with lazy content reads."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import mmap
8
+ from collections.abc import Iterator
9
+ from pathlib import Path
10
+
11
+ from .errors import (
12
+ BadMagicError,
13
+ ChecksumMismatchError,
14
+ TruncatedImageError,
15
+ UnsupportedTypeError,
16
+ )
17
+ from .format import (
18
+ ROMFH_MASK,
19
+ ROMFS_MAGIC,
20
+ ROMFS_SUPERBLOCK_CHECK_WINDOW,
21
+ EntryType,
22
+ _sum_words,
23
+ decode_name,
24
+ header_meta_size,
25
+ unpack_file_head,
26
+ unpack_superblock_head,
27
+ )
28
+ from .nodes import RomFSNode
29
+
30
+ _MAX_NAME = 128 # ROMFS_MAXFN
31
+
32
+
33
+ class RomFSReader:
34
+ """Read a romfs image from a file, building a node tree.
35
+
36
+ File contents are not loaded eagerly: the image is memory-mapped and
37
+ :meth:`read` slices the payload on demand.
38
+ """
39
+
40
+ def __init__(self, path: str | Path, *, verify: bool = True) -> None:
41
+ self._path = Path(path)
42
+ self._fd = open(self._path, "rb")
43
+ self._mm = mmap.mmap(self._fd.fileno(), 0, access=mmap.ACCESS_READ)
44
+
45
+ magic0, magic1, full_size, checksum = unpack_superblock_head(self._mm[:16])
46
+ if magic0 + magic1 != ROMFS_MAGIC:
47
+ raise BadMagicError(f"not a romfs image: bad magic {magic0 + magic1!r}")
48
+
49
+ self.full_size = full_size
50
+ self._checksum = checksum
51
+
52
+ if verify:
53
+ self._verify_checksum()
54
+
55
+ self.volume_name = self._read_volume_name()
56
+ self.root = self._build_root()
57
+
58
+ # --- public API --------------------------------------------------------
59
+
60
+ def walk(self) -> Iterator[tuple[str, RomFSNode]]:
61
+ """Yield ``(path, node)`` for every node under root (root itself excluded)."""
62
+ for child in self.root.children:
63
+ yield from child.walk()
64
+
65
+ def read(self, node: RomFSNode) -> bytes:
66
+ """Return the payload bytes of a regular file or symlink target."""
67
+ if node.type is EntryType.DIRECTORY:
68
+ raise TypeError(f"{node.name!r}: directories have no payload")
69
+ if node.data_offset is None:
70
+ raise TypeError(f"{node.name!r}: node has no data offset")
71
+ return bytes(self._mm[node.data_offset : node.data_offset + node.size])
72
+
73
+ def extract(self, outdir: str | Path) -> None:
74
+ """Write the whole tree to ``outdir`` (created if missing)."""
75
+ out = Path(outdir)
76
+ out.mkdir(parents=True, exist_ok=True)
77
+ for path, node in self.walk():
78
+ rel = Path(path)
79
+ if node.type is EntryType.DIRECTORY:
80
+ (out / rel).mkdir(parents=True, exist_ok=True)
81
+ elif node.type is EntryType.SYMLINK:
82
+ target = self.read(node).decode("utf-8")
83
+ (out / rel).parent.mkdir(parents=True, exist_ok=True)
84
+ (out / rel).symlink_to(target)
85
+ elif node.type is EntryType.REGULAR:
86
+ (out / rel).parent.mkdir(parents=True, exist_ok=True)
87
+ (out / rel).write_bytes(self.read(node))
88
+
89
+ def close(self) -> None:
90
+ self._mm.close()
91
+ self._fd.close()
92
+
93
+ def __enter__(self) -> RomFSReader:
94
+ return self
95
+
96
+ def __exit__(self, *exc: object) -> None:
97
+ self.close()
98
+
99
+ # --- internals ---------------------------------------------------------
100
+
101
+ def _read_volume_name(self) -> str:
102
+ # Volume name starts at offset 16, NUL-terminated (capped at ROMFS_MAXFN).
103
+ end = 16
104
+ limit = min(16 + _MAX_NAME, len(self._mm))
105
+ while end < limit and self._mm[end] != 0:
106
+ end += 1
107
+ return bytes(self._mm[16:end]).decode("utf-8", errors="replace")
108
+
109
+ def _verify_checksum(self) -> None:
110
+ # The kernel sums EVERY word in the first min(full_size, 512) bytes
111
+ # (including the checksum field) and requires the total to be zero:
112
+ # stored_checksum == -(sum of all other words). So we sum the raw
113
+ # block as-is and check for zero — no zeroing of the checksum field.
114
+ window = min(self.full_size, ROMFS_SUPERBLOCK_CHECK_WINDOW)
115
+ if window > len(self._mm):
116
+ raise TruncatedImageError(
117
+ f"image is {len(self._mm)} bytes but checksum window needs {window}"
118
+ )
119
+ if _sum_words(bytes(self._mm[:window])) & 0xFFFFFFFF != 0:
120
+ raise ChecksumMismatchError("superblock checksum does not sum to zero")
121
+
122
+ def _build_root(self) -> RomFSNode:
123
+ # Root header offset = align16(16 + len(volume_name) + 1), matching the
124
+ # kernel's `(ROMFH_SIZE + len + 1 + ROMFH_PAD) & ROMFH_MASK`.
125
+ root_off = header_meta_size(len(self.volume_name.encode("utf-8")))
126
+ root = self._parse_node(root_off)
127
+ if root.type is not EntryType.DIRECTORY:
128
+ raise BadMagicError(f"root entry at offset {root_off} is not a directory")
129
+ # The on-disk root entry is named "." (genromfs convention); expose it
130
+ # as a nameless root so child paths are clean ("watchface", not "./watchface").
131
+ root.name = ""
132
+ return root
133
+
134
+ def _parse_node(self, offset: int) -> RomFSNode:
135
+ if offset + 16 > len(self._mm):
136
+ raise TruncatedImageError(
137
+ f"file header at offset {offset} is out of bounds"
138
+ )
139
+
140
+ next_off, spec, size, _checksum = unpack_file_head(
141
+ self._mm[offset : offset + 16]
142
+ )
143
+ type_code = next_off & 0x07
144
+ try:
145
+ etype = EntryType(type_code)
146
+ except ValueError as e:
147
+ raise UnsupportedTypeError(
148
+ f"unknown entry type {type_code} at offset {offset}"
149
+ ) from e
150
+
151
+ name_len = self._strnlen(offset + 16)
152
+ name = decode_name(self._mm[offset + 16 : offset + 16 + name_len])
153
+ meta = header_meta_size(name_len)
154
+
155
+ node = RomFSNode(
156
+ name=name,
157
+ type=etype,
158
+ size=size,
159
+ spec_info=spec & ROMFH_MASK,
160
+ header_offset=offset,
161
+ _reader=self,
162
+ )
163
+ if etype is EntryType.HARDLINK:
164
+ # A hardlink's spec points at its destination header. genromfs uses
165
+ # hardlinks both for ".." (skipped in _parse_children) and for
166
+ # deduplicating identical files. Resolve file/symlink targets so
167
+ # read()/extract() see the linked content; directory targets are
168
+ # left unresolved to avoid cycles in the tree.
169
+ self._resolve_hardlink(node, spec & ROMFH_MASK)
170
+ elif etype in (EntryType.REGULAR, EntryType.SYMLINK):
171
+ node.data_offset = offset + meta
172
+ elif etype is EntryType.DIRECTORY:
173
+ self._parse_children(node, spec & ROMFH_MASK)
174
+
175
+ return node
176
+
177
+ def _resolve_hardlink(self, node: RomFSNode, target_off: int) -> None:
178
+ """Mirror a hardlink's file/symlink target so its content is readable."""
179
+ if not target_off or target_off == node.header_offset:
180
+ return
181
+ if target_off + 16 > len(self._mm):
182
+ return
183
+ t_next, _t_spec, t_size, _ = unpack_file_head(
184
+ self._mm[target_off : target_off + 16]
185
+ )
186
+ try:
187
+ t_type = EntryType(t_next & 0x07)
188
+ except ValueError:
189
+ return
190
+ if t_type not in (EntryType.REGULAR, EntryType.SYMLINK):
191
+ return
192
+ t_name_len = self._strnlen(target_off + 16)
193
+ t_meta = header_meta_size(t_name_len)
194
+ node.type = t_type
195
+ node.size = t_size
196
+ node.data_offset = target_off + t_meta
197
+
198
+ def _parse_children(self, parent: RomFSNode, first_off: int) -> None:
199
+ offset = first_off
200
+ while offset and offset + 16 <= len(self._mm):
201
+ # Peek the name first to skip the "." / ".." self/parent entries
202
+ # that genromfs emits at the head of every directory. "." is a DIR
203
+ # whose spec points back at the directory itself, so recursing into
204
+ # it would loop forever; ".." is a hardlink to the parent.
205
+ name_len = self._strnlen(offset + 16)
206
+ name = decode_name(self._mm[offset + 16 : offset + 16 + name_len])
207
+ if name not in (".", ".."):
208
+ child = self._parse_node(offset)
209
+ child.parent = parent
210
+ parent.children.append(child)
211
+ # Advance to the next sibling via this entry's `next` field. The
212
+ # offset lives in the high 28 bits; the low 4 bits carry type+exec.
213
+ next_raw = unpack_file_head(self._mm[offset : offset + 16])[0]
214
+ offset = next_raw & ROMFH_MASK
215
+
216
+ def _strnlen(self, offset: int) -> int:
217
+ """Length of the NUL-terminated name at ``offset`` (capped at ROMFS_MAXFN)."""
218
+ end = offset
219
+ limit = min(offset + _MAX_NAME, len(self._mm))
220
+ while end < limit and self._mm[end] != 0:
221
+ end += 1
222
+ return end - offset
223
+
224
+
225
+ __all__ = ["RomFSReader"]
romfs/writer.py ADDED
@@ -0,0 +1,207 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2026 Junbo Zheng
3
+ """Build a romfs image from a node tree or a local directory tree."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import os
8
+ from pathlib import Path
9
+ from typing import BinaryIO
10
+
11
+ from .format import (
12
+ ALIGN,
13
+ ROMFS_IMAGE_ALIGN,
14
+ ROMFS_SUPERBLOCK_CHECK_WINDOW,
15
+ EntryType,
16
+ align_up,
17
+ encode_name,
18
+ header_checksum,
19
+ header_meta_size,
20
+ pack_file_head,
21
+ pack_superblock_head,
22
+ superblock_checksum,
23
+ )
24
+ from .nodes import RomFSNode
25
+
26
+
27
+ class RomFSWriter:
28
+ """Assemble a romfs image from a root :class:`RomFSNode` tree.
29
+
30
+ Build a tree with :meth:`from_directory` (or by hand), then call
31
+ :meth:`write` to emit the image.
32
+ """
33
+
34
+ def __init__(self, root: RomFSNode, volume_name: str = "") -> None:
35
+ if root.type is not EntryType.DIRECTORY:
36
+ raise ValueError("root node must be a directory")
37
+ self.root = root
38
+ self.volume_name = volume_name
39
+
40
+ # --- construction ------------------------------------------------------
41
+
42
+ @classmethod
43
+ def from_directory(cls, root_dir: str | Path, volume_name: str = "") -> RomFSWriter:
44
+ """Build a writer from a local directory tree.
45
+
46
+ - directories -> DIRECTORY nodes (recursed)
47
+ - symlinks -> SYMLINK nodes (target stored as payload)
48
+ - regular files-> REGULAR nodes (payload copied from disk)
49
+ Other entry types (devices, fifos, sockets) are skipped with a warning.
50
+ """
51
+ root_dir = Path(root_dir)
52
+ if not root_dir.is_dir():
53
+ raise NotADirectoryError(f"not a directory: {root_dir}")
54
+ root = RomFSNode(name="", type=EntryType.DIRECTORY)
55
+ cls._scan(root_dir, root)
56
+ return cls(root, volume_name=volume_name)
57
+
58
+ @classmethod
59
+ def _scan(cls, dir_path: Path, node: RomFSNode) -> None:
60
+ for entry in sorted(dir_path.iterdir(), key=lambda p: p.name):
61
+ child = cls._make_node(entry)
62
+ if child is not None:
63
+ child.parent = node
64
+ node.children.append(child)
65
+
66
+ @classmethod
67
+ def _make_node(cls, path: Path) -> RomFSNode | None:
68
+ if path.is_symlink():
69
+ target = os.readlink(path)
70
+ tgt_bytes = target.encode("utf-8")
71
+ return RomFSNode(
72
+ name=path.name,
73
+ type=EntryType.SYMLINK,
74
+ size=len(tgt_bytes),
75
+ target=target,
76
+ )
77
+ if path.is_dir():
78
+ node = RomFSNode(name=path.name, type=EntryType.DIRECTORY)
79
+ cls._scan(path, node)
80
+ return node
81
+ if path.is_file():
82
+ return RomFSNode(
83
+ name=path.name,
84
+ type=EntryType.REGULAR,
85
+ size=path.stat().st_size,
86
+ src_path=str(path),
87
+ )
88
+ # Skip devices / fifos / sockets — out of scope for this writer.
89
+ return None
90
+
91
+ # --- emission ----------------------------------------------------------
92
+
93
+ def write(self, out: str | Path | BinaryIO) -> None:
94
+ """Write the romfs image to a path or open binary stream."""
95
+ image = self._build_image()
96
+ if isinstance(out, (str, os.PathLike)):
97
+ Path(out).write_bytes(image)
98
+ else:
99
+ out.write(image)
100
+
101
+ def _build_image(self) -> bytes:
102
+ # 1. Assign header offsets via pre-order DFS.
103
+ root_off = header_meta_size(len(self.volume_name.encode("utf-8")))
104
+ content_end = self._layout(self.root, root_off)
105
+ total = align_up(content_end, ROMFS_IMAGE_ALIGN)
106
+
107
+ # 2. Render into a zeroed buffer of the final size.
108
+ buf = bytearray(total)
109
+ self._render(self.root, buf)
110
+
111
+ # 3. Fill the superblock (magic + size + checksum) last.
112
+ self._render_superblock(buf, total)
113
+
114
+ return bytes(buf)
115
+
116
+ # --- layout ------------------------------------------------------------
117
+
118
+ def _layout(self, node: RomFSNode, offset: int) -> int:
119
+ """Assign ``header_offset``/``data_offset``; return the next free offset."""
120
+ node.header_offset = offset
121
+ meta = header_meta_size(len(node.name.encode("utf-8")))
122
+
123
+ if node.type is EntryType.DIRECTORY:
124
+ cursor = offset + meta
125
+ for child in node.children:
126
+ cursor = self._layout(child, cursor)
127
+ if node.children:
128
+ first = node.children[0].header_offset
129
+ assert first is not None
130
+ node.spec_info = first
131
+ else:
132
+ node.spec_info = 0
133
+ return cursor
134
+
135
+ # Regular file or symlink: payload follows the (padded) header.
136
+ node.data_offset = offset + meta
137
+ return offset + meta + align_up(node.size, ALIGN)
138
+
139
+ # --- rendering ---------------------------------------------------------
140
+
141
+ def _render(self, node: RomFSNode, buf: bytearray) -> None:
142
+ offset = node.header_offset
143
+ assert offset is not None
144
+
145
+ next_off = self._next_sibling_offset(node)
146
+ type_bits = int(node.type) & 0x07
147
+ next_field = (next_off | type_bits) & 0xFFFFFFFF
148
+
149
+ # Pack the header with checksum=0, then fix up the checksum.
150
+ name_field = encode_name(node.name)
151
+ head = pack_file_head(next_field, node.spec_info, node.size, 0) + name_field
152
+ checksum = header_checksum(head)
153
+ head = (
154
+ pack_file_head(next_field, node.spec_info, node.size, checksum) + name_field
155
+ )
156
+ buf[offset : offset + len(head)] = head
157
+
158
+ if node.type is EntryType.REGULAR:
159
+ assert (
160
+ node.src_path is not None
161
+ ), f"regular node {node.name!r} has no src_path"
162
+ data = Path(node.src_path).read_bytes()
163
+ self._write_payload(buf, node, data)
164
+ elif node.type is EntryType.SYMLINK:
165
+ assert node.target is not None, f"symlink node {node.name!r} has no target"
166
+ data = node.target.encode("utf-8")
167
+ self._write_payload(buf, node, data)
168
+ elif node.type is EntryType.DIRECTORY:
169
+ for child in node.children:
170
+ self._render(child, buf)
171
+
172
+ def _write_payload(self, buf: bytearray, node: RomFSNode, data: bytes) -> None:
173
+ assert node.data_offset is not None
174
+ buf[node.data_offset : node.data_offset + len(data)] = data
175
+ # Trailing padding stays zero (buffer is pre-zeroed).
176
+
177
+ def _next_sibling_offset(self, node: RomFSNode) -> int:
178
+ if node.parent is None:
179
+ # Root has no siblings.
180
+ return 0
181
+ siblings = node.parent.children
182
+ idx = siblings.index(node)
183
+ if idx + 1 < len(siblings):
184
+ nxt = siblings[idx + 1].header_offset
185
+ assert nxt is not None
186
+ return nxt
187
+ return 0
188
+
189
+ # --- superblock --------------------------------------------------------
190
+
191
+ def _render_superblock(self, buf: bytearray, total: int) -> None:
192
+ # Magic + full_size + checksum(=0 placeholder) + volume name field.
193
+ head = pack_superblock_head(total, 0)
194
+ name_field = encode_name(self.volume_name)
195
+ buf[0 : len(head)] = head
196
+ buf[len(head) : len(head) + len(name_field)] = name_field
197
+
198
+ # Checksum covers the first min(total, 512) bytes with the checksum
199
+ # field (offset 12) zeroed.
200
+ window = min(total, ROMFS_SUPERBLOCK_CHECK_WINDOW)
201
+ block = bytes(buf[:window])
202
+ checksum = superblock_checksum(block)
203
+ final_head = pack_superblock_head(total, checksum)
204
+ buf[0 : len(final_head)] = final_head
205
+
206
+
207
+ __all__ = ["RomFSWriter"]
@@ -0,0 +1,151 @@
1
+ Metadata-Version: 2.4
2
+ Name: romfs
3
+ Version: 0.0.1
4
+ Summary: Pure-Python reader and writer for Linux romfs (-rom1fs-) filesystem images.
5
+ Project-URL: Homepage, https://github.com/Junbo-Zheng/romfs
6
+ Project-URL: Issues, https://github.com/Junbo-Zheng/romfs/issues
7
+ Author-email: Junbo Zheng <Junbo-Zheng@users.noreply.github.com>
8
+ License: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: embedded,filesystem,image,initrd,rom1fs,romfs
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Software Development :: Build Tools
21
+ Classifier: Topic :: System :: Filesystems
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Provides-Extra: dev
25
+ Requires-Dist: black; extra == 'dev'
26
+ Requires-Dist: build; extra == 'dev'
27
+ Requires-Dist: mypy; extra == 'dev'
28
+ Requires-Dist: pytest-cov; extra == 'dev'
29
+ Requires-Dist: pytest>=7.0; extra == 'dev'
30
+ Requires-Dist: ruff; extra == 'dev'
31
+ Requires-Dist: twine; extra == 'dev'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # romfs
35
+
36
+ [![PyPI](https://img.shields.io/pypi/v/romfs.svg)](https://pypi.org/project/romfs/)
37
+ [![CI](https://github.com/Junbo-Zheng/romfs/actions/workflows/ci.yml/badge.svg)](https://github.com/Junbo-Zheng/romfs/actions/workflows/ci.yml)
38
+ [![Python](https://img.shields.io/pypi/pyversions/romfs.svg)](https://pypi.org/project/romfs/)
39
+ [![License](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE)
40
+
41
+ > Pure-Python reader and writer for Linux romfs (`-rom1fs-`) filesystem images.
42
+ > Standard library only, no runtime dependencies.
43
+
44
+ `romfs` lets you build, inspect, and extract the small read-only filesystem
45
+ images the Linux kernel uses for initrds and embedded root filesystems. Images
46
+ produced by the writer are byte-compatible with `mount -t romfs` and
47
+ interchangeable with `genromfs`; the reader parses any such image, including
48
+ real `genromfs` output with `.`/`..` self-links and dedup hardlinks.
49
+
50
+ ## Features
51
+
52
+ - **Read** an image into a node tree; list entries and read file contents
53
+ lazily via `mmap` — large images don't blow up memory.
54
+ - **Write** an image from a local directory tree, preserving the structure,
55
+ regular files, and symbolic links.
56
+ - **CLI** with `list`, `extract`, `pack`, and `info` subcommands.
57
+ - **Importable library** API for embedding in other tools.
58
+ - Byte-exact conformance with the kernel romfs format: 16-byte alignment,
59
+ big-endian, superblock + header checksums.
60
+ - Entries sorted by name for a deterministic, diff-friendly layout.
61
+
62
+ > [!NOTE]
63
+ > The writer lays out entries sorted by name, so two versions of the same
64
+ > resource tree produce byte-stable images — keeping binary diffs (delta
65
+ > packages) small.
66
+
67
+ ## Installation
68
+
69
+ ```bash
70
+ pip install romfs
71
+ ```
72
+
73
+ Run from source with no install:
74
+
75
+ ```bash
76
+ ./main.py <args>
77
+ ```
78
+
79
+ ## Quick start
80
+
81
+ ```bash
82
+ # Pack a folder tree into a single romfs image
83
+ romfs pack ./rootfs -o rootfs.img -n myvol
84
+
85
+ # List the file tree (type, size, path)
86
+ romfs list rootfs.img
87
+
88
+ # Extract one file to stdout, or everything to a directory
89
+ romfs extract rootfs.img etc/init.d/rcS
90
+ romfs extract rootfs.img -o ./out
91
+
92
+ # Show header info and verify the superblock checksum
93
+ romfs info rootfs.img --verify
94
+ ```
95
+
96
+ ## CLI reference
97
+
98
+ ```text
99
+ romfs list <image> list the file tree (path, type, size)
100
+ romfs extract <image> [-o OUTDIR] [PATH] extract all, or one entry to stdout
101
+ romfs pack <srcdir> -o <image> [-n NAME] build an image from a directory tree
102
+ romfs info <image> [--verify] print header info + checksum check
103
+ ```
104
+
105
+ `romfs -V` prints the version; `romfs -h` shows help.
106
+
107
+ ## Library API
108
+
109
+ ```python
110
+ from romfs import RomFSReader, RomFSWriter, EntryType
111
+
112
+ # Read an image
113
+ with RomFSReader("rootfs.img") as r:
114
+ print(r.volume_name, r.full_size)
115
+ for path, node in r.walk():
116
+ print(f"{node.type.name:9} {node.size:>8} {path}")
117
+ # File contents are sliced from the mmap on demand
118
+ data = r.read(r.root.children[0])
119
+
120
+ # Build an image from a directory tree
121
+ RomFSWriter.from_directory("./rootfs", volume_name="myvol").write("out.img")
122
+ ```
123
+
124
+ ## Supported entry types
125
+
126
+ | Type | Read | Write |
127
+ |-------------------------------------|:----:|:-----:|
128
+ | Regular file | yes | yes |
129
+ | Directory | yes | yes |
130
+ | Symlink | yes | yes |
131
+ | Hardlink / device / socket / fifo | yes | no |
132
+
133
+ > [!NOTE]
134
+ > romfs does not store per-file Unix mode bits in the standard format, so the
135
+ > kernel assigns fixed default modes. Permissions are not preserved on write.
136
+ > Hardlinks and special files are parsed on read but not emitted on write.
137
+
138
+ ## Development
139
+
140
+ ```bash
141
+ pip install -e ".[dev]" # pytest, black, ruff, mypy, build, twine
142
+ pytest # runs against src/ directly, no install needed
143
+ black src tests main.py # format
144
+ ruff check src tests # lint
145
+ mypy src # type check
146
+ python -m build # build sdist + wheel into dist/
147
+ ```
148
+
149
+ CI runs black + ruff + mypy + pytest across Python 3.10-3.13, plus a packaging
150
+ job that builds the wheel and tests the installed package. Releases publish to
151
+ PyPI automatically on a GitHub Release via Trusted Publishing (OIDC).
@@ -0,0 +1,12 @@
1
+ romfs/__init__.py,sha256=BGahrbhMkm18wv3GS0EXnuq5RsXDlUvYTm4YoxSuEIw,662
2
+ romfs/cli.py,sha256=ThdNdJlNFk-H5HZKfAyRlTZpT5SliQj-ipfglPAsSzQ,4574
3
+ romfs/errors.py,sha256=1jElx2KkY2RAXVyu-D2dyOWcHhhkm3QWN159UU0WN2o,787
4
+ romfs/format.py,sha256=H9xXDgqNGVOB47J-s-BbhNUd1NNpSbm-rpg0l31XYRg,5980
5
+ romfs/nodes.py,sha256=L9-qqQFZyeUyNYzKOxGqGEJ2Mp9Z_Puxt5SrmwbLVBA,2023
6
+ romfs/reader.py,sha256=uOvWUh_aEy1rx7uEgbSenTeD6ZJbGRzli6vbPYeRLNo,8866
7
+ romfs/writer.py,sha256=2QpBzQmJaxJVNsbOuIumSPPPsmcutGNXeybx05kV_G0,7614
8
+ romfs-0.0.1.dist-info/METADATA,sha256=6H304Et4CgIipnDR6sWpGXuj7hvN_8w7QHvLimX00JM,5606
9
+ romfs-0.0.1.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
10
+ romfs-0.0.1.dist-info/entry_points.txt,sha256=1rIx7DcYmcxf80k0zUv6N4FnJsgBNRy4eCTEuMJsg-M,41
11
+ romfs-0.0.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
12
+ romfs-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ romfs = romfs.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.