msl
MSL format constants and enumerations (Memory Slice Specification v1.0.0 — binary format 1.1).
Magic bytes and all IntEnum/IntFlag types from the specification tables.
- class HeaderFlag[source]
Bases:
IntFlag- IMPORTED = 1
- INVESTIGATION = 2
- ENCRYPTED = 4
- __new__(value)
- class BlockType[source]
Bases:
IntEnumBlock type registry (spec Table 9).
- INVALID = 0
- MEMORY_REGION = 1
- MODULE_ENTRY = 2
- MODULE_LIST_INDEX = 16
- THREAD_CONTEXT = 17
- FILE_DESCRIPTOR = 18
- NETWORK_CONNECTION = 19
- ENVIRONMENT_BLOCK = 20
- SECURITY_TOKEN = 21
- KEY_HINT = 32
- IMPORT_PROVENANCE = 48
- PROCESS_IDENTITY = 64
- RELATED_DUMP = 65
- SYSTEM_CONTEXT = 80
- PROCESS_TABLE = 81
- CONNECTION_TABLE = 82
- HANDLE_TABLE = 83
- CONNECTIVITY_TABLE = 85
- PHYSICAL_MEMORY_MAP = 89
- END_OF_EXTENSION = 4094
- END_OF_CAPTURE = 4095
- VAS_MAP = 4097
- POINTER_GRAPH = 4099
- __new__(value)
- class BlockFlag[source]
Bases:
IntFlagPer-block flags (spec Table 7).
- COMPRESSED = 1
- COMP_ZSTD = 2
- COMP_LZ4 = 4
- HAS_KEY_HINTS = 8
- HAS_CHILDREN = 16
- CONTINUATION = 32
- __new__(value)
- class PageState[source]
Bases:
IntEnumFour-state page acquisition model (spec Table 24 / Section 7).
NOT_RESIDENT(0b11) is a mapped page that was not resident at capture time. It contributes no captured bytes to PageData.RESERVEDis kept as a backwards-compatible alias of the same value (older code named it that way and treated it as FAILED).- CAPTURED = 0
- FAILED = 1
- UNMAPPED = 2
- NOT_RESIDENT = 3
- RESERVED = 3
- __new__(value)
- class Protection[source]
Bases:
IntFlagMemory region protection flags (spec Section 5.1).
- READ = 1
- WRITE = 2
- EXECUTE = 4
- GUARD = 8
- COW = 16
- __new__(value)
- class RegionType[source]
Bases:
IntEnumMemory region types (spec Section 5.1).
- UNKNOWN = 0
- HEAP = 1
- STACK = 2
- IMAGE = 3
- MAPPED_FILE = 4
- ANONYMOUS = 5
- SHARED_MEM = 6
- OTHER = 255
- __new__(value)
- class ThreadState[source]
Bases:
IntEnumScheduler state of a thread (Thread Context block, spec Table 19a).
- UNKNOWN = 0
- RUNNING = 1
- SLEEPING = 2
- STOPPED = 3
- WAITING = 4
- UNINTERRUPTIBLE = 5
- HALTED = 6
- ZOMBIE = 7
- __new__(value)
- class VasNameSource[source]
Bases:
IntEnumHow a VAS Map entry’s MappedPath was obtained (spec 5.8).
- UNSPECIFIED = 0
- LIVE = 1
- SOURCE_METADATA = 2
- SYNTHESIZED = 3
- __new__(value)
- class OSType[source]
Bases:
IntEnum- WINDOWS = 0
- LINUX = 1
- MACOS = 2
- ANDROID = 3
- IOS = 4
- FREEBSD = 5
- UNKNOWN = 65535
- __new__(value)
- class ArchType[source]
Bases:
IntEnum- X86 = 0
- X86_64 = 1
- ARM64 = 2
- ARM32 = 3
- UNKNOWN = 65535
- __new__(value)
- class SourceFormat[source]
Bases:
IntEnumSource artifact format for the IMPORT_PROVENANCE block source_format.
The specification defines the wire codes. This enum also represents legacy MemDiver origins and internal classifications. Use
memdiver.msl.source_format.wire_source_format()to encode them.- RAW_DUMP = 1
- ELF_CORE = 2
- MINIDUMP = 3
- MSL = 4
- REGIONED_RAW = 5
- OTHER = 65535
- MACOS_CORE = 65540
- PROCDUMP = 65541
- __new__(value)
- class MslKeyType[source]
Bases:
IntEnumCrypto key type codes (spec Table 17).
- UNKNOWN = 0
- PRE_MASTER_SECRET = 1
- MASTER_SECRET = 2
- SESSION_KEY = 3
- HANDSHAKE_SECRET = 4
- APP_TRAFFIC_SECRET = 5
- RSA_PRIVATE_KEY = 6
- ECDH_PRIVATE_KEY = 7
- IKE_SA_KEY = 8
- ESP_AH_KEY = 9
- SSH_SESSION_KEY = 10
- WIREGUARD_KEY = 11
- ML_KEM_PRIVATE_KEY = 12
- OTHER = 65535
- __new__(value)
- class MslProtocol[source]
Bases:
IntEnumProtocol codes (spec Table 17).
- UNKNOWN = 0
- TLS_12 = 1
- TLS_13 = 2
- DTLS_12 = 3
- DTLS_13 = 4
- QUIC = 5
- IKEV2_IPSEC = 6
- SSH = 7
- WIREGUARD = 8
- PQ_TLS = 9
- OTHER = 65535
- __new__(value)
- class Confidence[source]
Bases:
IntEnumKey hint confidence levels (spec Section 5.6).
- SPECULATIVE = 0
- HEURISTIC = 1
- CONFIRMED = 2
- __new__(value)
- class KeyState[source]
Bases:
IntEnumKey lifecycle state (spec Section 5.6).
- UNKNOWN = 0
- ACTIVE = 1
- EXPIRED = 2
- __new__(value)
- class HandleType[source]
Bases:
IntEnumHandle Table entry type discriminator (spec Table 24, uint16).
- UNKNOWN = 0
- FILE = 1
- DIR = 2
- SOCKET = 3
- PIPE = 4
- MUTEX = 5
- TIMER = 6
- OTHER = 7
- __new__(value)
- class ConnRowType[source]
Bases:
IntEnumConnectivity Table row-type discriminator (spec Table 26, uint8).
- IPV4_ROUTE = 1
- IPV6_ROUTE = 2
- ARP_ENTRY = 3
- PACKET_SOCKET = 4
- IFACE_STATS = 5
- SOCKET_FAMILY_AGG = 6
- MIB_COUNTER = 7
- __new__(value)
- class HashAlgo[source]
Bases:
IntEnumIntegrity hash algorithm selector (file header offset 0x3D, spec Table 12).
All registered algorithms produce 32-byte output, so field layouts are independent of the choice. Applies to PrevHash, EoC FileHash, DiskHash — NOT to HKDF key derivation (which always uses BLAKE3).
- BLAKE3 = 0
- SHA256 = 1
- SHA512_256 = 2
- OTHER = 255
- __new__(value)
- class EncAlgo[source]
Bases:
IntEnumAEAD cipher suite (encryption extension offset 0x40, spec Table 30).
- AES_256_GCM = 1
- XCHACHA20_POLY1305 = 2
- __new__(value)
- class KdfType[source]
Bases:
IntEnumKey derivation function (encryption extension offset 0x41, spec §10.5).
- NONE = 0
- ARGON2ID = 1
- __new__(value)
- class KeyEncap[source]
Bases:
IntEnumKey encapsulation mechanism (encryption extension offset 0x42, spec Table 31).
- NONE = 0
- X25519 = 1
- ML_KEM_768 = 2
- ML_KEM_1024 = 3
- X25519_ML_KEM_768 = 4
- OTHER = 255
- __new__(value)
- class TagStatus[source]
Bases:
EnumResult of AEAD tag verification, surfaced to the user by MslReader.
Distinguishes the four states a consumer must communicate (spec §10, §14.2): a plaintext file, a verified decryption, a failed/tampered decryption, and an encrypted file opened without a key.
- NOT_ENCRYPTED = 'not_encrypted'
- VALID = 'valid'
- CORRUPTED = 'corrupted'
- MISSING_KEY = 'missing_key'
- class NodeKind[source]
Bases:
IntEnumPOINTER_GRAPH node-kind discriminator (uint8).
Distinguishes how to interpret the node’s 64-bit value field.
- ADDRESS = 1
- OFFSET = 2
- SYMBOL = 3
- __new__(value)
- class EdgeKind[source]
Bases:
IntEnumPOINTER_GRAPH edge-kind discriminator (uint8).
- POINTER = 1
- CALL = 2
- IMPORT = 3
- __new__(value)
Define the Memory Slice format and its decoded record types.
Use the integrity verifier to check BLAKE3 or SHA-256 block chains. The reader decodes Zstandard or LZ4 payloads when their flags request it.
MSL file reader with mmap-backed, endianness-aware parsing.
- class CapturedRun[source]
Bases:
NamedTupleOne contiguous run of CAPTURED pages, located in the block buffer.
The unit of
MslReader.captured_run_index(). Everything a reader of.mslbytes needs in order to serve a window WITHOUT walking the container: where the run lives in virtual address space, where it lives in the flat"vas"stream, and where its bytes are in the buffer.lengthis the run’s NOMINAL size (pages * page_size);availis how many of those bytes the buffer actually holds. The two differ only for a container truncated mid-payload, and keeping them apart is what lets a caller report the run’s true extent while copying only real bytes.blockisNonefor an uncompressed region:buf_offsetis then an offset into the reader’s block buffer (mmap / decrypted stream). For a COMPRESSED region block it is that block’s header, andbuf_offsetis an offset into the block’s DECOMPRESSED payload — the on-disk bytes are codec output, not memory. Read run bytes throughMslReader.run_view()/MslReader.iter_find_run(), which handle both cases.
- class CapturedRunIndex[source]
Bases:
NamedTupleCapturedRunruns plus the keys a read path bisects them by.runsis invas_offsetorder — the orderMslDumpSource.iter_ranges()yields in, which is what makesvas_offsetthe flat"vas"stream offset.by_vais the same runs ordered by virtual address, because a"va"window has to find the runs that overlap an address and region base addresses are not guaranteed to arrive in VA order.The two
*_startstuples are the bisect keys for their respective orderings, materialized once so a lookup never rebuilds them.- runs: Tuple[CapturedRun, ...]
Alias for field number 0
- by_va: Tuple[CapturedRun, ...]
Alias for field number 1
- static __new__(_cls, runs, by_va, va_starts, vas_starts)
Create new instance of CapturedRunIndex(runs, by_va, va_starts, vas_starts)
- Parameters:
runs (Tuple[CapturedRun, ...])
by_va (Tuple[CapturedRun, ...])
- FIND_WINDOW = 8388608
Window for searching a buffer that has no
find(the lazily decrypted view): the most plaintext one search step holds at a time.
- class MslReader[source]
Bases:
objectRead blocks and captured memory from a mapped MSL file.
Use the reader as a context manager to open and close the file. For an encrypted capture, supply the applicable key material at construction and inspect
tag_statusbefore reading blocks.Block collectors cache decoded capture records in file order. They skip malformed records with a warning. Use the extension methods to inspect blocks written after End of Capture.
- open()[source]
Map the file and set its key status.
For an encrypted capture with key material, verify the authentication tag before opening the decrypted stream.
- Return type:
None
- probe_key()[source]
Check key material against the first block without authenticating the file.
An open reader returns its existing
tag_status. For a closed reader, parse the header, derive the content key, and check the first block’s magic. The reader closes before returning.In this preflight,
VALIDmeans only that the magic matched. An incorrect key can match by chance. Changes outside those bytes can go undetected. Useopen()for full tag verification. Header errors propagate to the caller.- Return type:
- close()[source]
Release cached data, the memory map, and the file handle.
Release any outstanding memoryviews from this reader before closing.
- Return type:
None
- property file_header: MslFileHeader
- SUPPORTED_MAJOR_VERSION = 1
- KNOWN_MAX_MINOR_VERSION = 1
- property post_tag_offset: int | None
Return the offset after the verified primary AEAD tag, if available.
- scan_extension_segments()[source]
Frame the extension segments after the EoC (header-only, cached).
Walks blocks from
_extension_start(); each run up to and including an End-of-Extension block is one segment. A run that hits EOF, non-magic bytes or a block that fails framing before a terminator is returned as an unterminated segment (terminatorNone) and ends the scan — everything from there on is trailing data. No verification happens here (seeintegrity.verify_extension_segments()).- Return type:
List[ExtensionSegment]
- iter_extension_blocks(include_unverified=False)[source]
Iterate
(header, payload)over the extension segments’ blocks.Terminator blocks are included. By default only verified segments (chain continuity for plaintext files, SegmentHash, BlockCount — spec consumer rule 23) are yielded; include_unverified also walks unterminated or failing segments, whose blocks MUST NOT be presented as verified. Payloads are decompressed like
iter_blocks. Blocks of verified sealed segments (spec 10.8, encrypted files) follow, in SegIndex order, withhdr.seal_indexset; sealed segments that fail are never yielded, not even when unverified segments are requested.
- sealed_segments()[source]
Verified sealed segments after the primary AEAD tag (cached).
Only for a tag-verified container with
CipherLen != 0; empty otherwise. Each is amemdiver.msl.sealed.SealedSegmentwhose tag and plaintext segment both verified; their blocks follow the in-stream segments’ initer_extension_blocks().- Return type:
- property sealed_trailing_bytes: int
Bytes after the primary tag not covered by a verified sealed segment.
- property trailing_bytes: int
Count unverified bytes after End of Capture within the block buffer.
Use
sealed_trailing_bytesfor data after the primary encryption tag.
- iter_blocks(merge_cont=True)[source]
Iterate blocks; merges continuation blocks when merge_cont is True.
- read_bytes(offset, length)[source]
Read raw bytes from the block region at the given offset.
Offsets are relative to the same buffer block offsets use: the mmap for plaintext files, the decrypted stream for encrypted files.
- property buffer_length: int
Bytes addressable by
read_bytes()/read_view().Zero when the reader is closed. Exposed so a caller can decide how much of a block’s declared payload a truncated container actually holds WITHOUT reading the payload to find out.
- read_view(offset, length)[source]
Return a view of a byte range in the reader’s buffer coordinates.
A mapped plaintext file uses a view without copying. The lazy encrypted reader returns a view of the decrypted copy. Release the view before closing the reader.
- Parameters:
- Return type:
- iter_find(needle, offset, length)[source]
Yield buffer offsets of needle inside
[offset, offset+length).Matches must lie wholly inside the (buffer-clamped) range; overlapping matches are all reported, ascending — the same answer as
find_all_offsets(read_bytes(offset, length), needle)shifted byoffset, without the copy. Plaintext buffers (the mmap, or the one-shot plaintextbytes) are searched in place with boundedfind(needle, start, end); a lazily decrypted view has nofind, so it is decrypted in bounded windows (_iter_find_windowed()). An empty needle yields nothing (seecore.dump_io.find_all_offsetsfor why that guard is load-bearing on an mmap).
- decompressed_payload(hdr)[source]
Read one block’s payload and keep it as the most recent cache entry.
A subsequent request for the same block can reuse the bytes. Reading a different payload replaces the cache.
- Parameters:
hdr (MslBlockHeader)
- Return type:
- run_span(run)[source]
Bytes of run that can actually be read (
read_viewclamping).- Parameters:
run (CapturedRun)
- Return type:
- run_view(run, begin, length)[source]
lengthbytes of run startingbeginbytes into it.Uncompressed runs:
read_view()(zero-copy on an mmap). Compressed runs: a view into the block’s decompressed payload.- Parameters:
run (CapturedRun)
begin (int)
length (int)
- Return type:
- iter_find_run(run, needle)[source]
Run-relative offsets of needle inside run’s readable bytes.
Same answer as
find_all_offsets(run_view(run, 0, run_span(run)), needle)without copying the run: an uncompressed run is searched in place (iter_find()), a compressed one inside its cached decompressed payload with boundedfind(needle, start, end).- Parameters:
run (CapturedRun)
needle (bytes)
- Return type:
- read_block_payload(hdr)[source]
Read and decompress a block’s payload bytes.
A block of a sealed segment (
hdr.seal_index) is read from that segment’s verified plaintext.- Parameters:
hdr (MslBlockHeader)
- Return type:
- iter_blocks_of_type(*block_types)[source]
Like
iter_blocks(), but reads payloads only for block_types.Every other block is skipped at the header level, so asking for the (small) module tables never copies or decompresses region payloads. Continuations of a wanted type are merged as in
iter_blocks().
- iter_region_headers()[source]
Decode every MEMORY_REGION from its 0x20 header + page map only.
Uncompressed blocks are read with two bounded views (fixed header, then header + PageStateMap); page data is never touched. A compressed block has no random access, so its payload is decompressed one block at a time and dropped after decoding (never cached). The DECODED region is cached (
_decoded_region(), shared withcollect_regions()), so a second iteration re-reads and re-decodes nothing. Continuation blocks are skipped: the fixed header and page map live in the parent. Malformed blocks are skipped with a warning, as in_collect. Yields nothing for an encrypted file opened without key material.- Return type:
Iterator[MslMemoryRegion]
- collect_regions()[source]
Decode and cache Memory Region metadata in merged block order.
The result contains headers and page maps. Uncompressed blocks require only the metadata bytes. A compressed block can require decompression of the full payload. Skip malformed regions with a warning.
- Return type:
List[MslMemoryRegion]
- captured_run_index()[source]
Index captured runs by virtual address and packed stream offset.
Visit regions in base-address order and pages in their original order. This gives each run the same packed offset as the dump source’s
vasview. Record the available bytes separately from the extent claimed by the page map.Use region metadata to build the index. Compressed blocks can require decompression to determine payload lengths. The reader caches the index until it closes.
- Return type:
- collect_key_hints()[source]
Return the key hints stored in the capture segment.
- Return type:
List[MslKeyHint]
- collect_modules()[source]
Return decoded module entries in file order.
- Return type:
List[MslModuleEntry]
- collect_process_identity()[source]
Return the process identity records stored in the capture.
- Return type:
List[MslProcessIdentity]
- collect_vas_map()[source]
Capture-segment VAS_MAP blocks, raw and in file order.
For the map the file actually asserts (last one wins, extension segments included — spec 5.8) use
effective_vas_map().- Return type:
List[MslVasMap]
- Return type:
List[MslRelatedDump]
- collect_import_provenance()[source]
Return the recorded source and importer details for the capture.
- Return type:
List[MslImportProvenance]
- collect_processes()[source]
Return the captured system process tables.
- Return type:
List[MslProcessTable]
- collect_connections()[source]
Return the captured process connection tables.
- Return type:
List[MslConnectionTable]
- collect_handles()[source]
Return the captured process handle tables.
- Return type:
List[MslHandleTable]
- collect_physical_memory_map()[source]
Physical Memory Map (0x0059) blocks, in file order (spec 5.9).
- Return type:
List[MslPhysicalMemoryMap]
- collect_thread_contexts()[source]
THREAD_CONTEXT (0x0011) blocks per spec 5.7 (
MslThreadContext; a malformed one decodes toMslGenericBlock).- Return type:
- collect_system_context()[source]
Collect SYSTEM_CONTEXT (0x0050) blocks per spec §6.2 Table 20.
- Return type:
- collect_end_of_extension()[source]
Decoded End-of-Extension blocks of every verified segment.
- Return type:
List[MslEndOfExtension]
- collect_pointer_graphs()[source]
Collect POINTER_GRAPH blocks (0x1003) from verified extension segments.
The block lives after the EoC (inside the AEAD stream when encrypted), so it comes from
iter_extension_blocks()rather thaniter_blocks(). Returns an empty list when the file has no verified segment carrying one — the common case.- Return type:
List[MslPointerGraph]
The share-class map (
memdiver.shareclass/1) of the verified segments, or None.A producer-defined Structural block (spec 4.3/4.6), so it is read only from verified extension segments; the last one in file order wins. Returns a
memdiver.msl.share_classes.ShareClassMap.
- collect_extension_vas_maps()[source]
Collect VAS_MAP blocks (0x1001) from verified extension segments.
In-stream segments then verified sealed ones, in file order (via
iter_extension_blocks()). A malformed block is skipped with a warning, as in_collect().- Return type:
List[MslVasMap]
- effective_vas_map()[source]
The VAS map the file says applies, or
Nonewhen it has none.Spec 5.8 / consumer rule 25: the LAST VAS map in file order supersedes earlier ones, including maps in verified extension (4.6) and sealed (10.8) segments. Segment maps always follow capture-segment ones, so the result came from a segment exactly when
collect_extension_vas_maps()is non-empty.- Return type:
MslVasMap | None
- probe_key(path, *, key=None, passphrase=None, kem_private_key=None)[source]
MslReader.probe_key()for path: the key checked on block 0 only.NOT_ENCRYPTED / VALID / MISSING_KEY / CORRUPTED, with the limits that method documents (a ciphertext tampered beyond block 0 is not detected).
Write Memory Slice captures and extension segments.
The writer builds the capability bitmap from the queued blocks. Memory regions carry a four-state page map. The writer can stream region data to limit memory use.
- default_hash_algo(hash_algo)[source]
Make every
MslWriterbuilt inside the block (with no explicithash_algo) use hash_algo, e.g. to have an importer or materializer that builds its own writer emit a SHA-256 chain.- Parameters:
hash_algo (int)
- pinned_default_hash_algo()[source]
The HashAlgo an enclosing
default_hash_algo()block pinned, else None.- Return type:
HashAlgo | None
- resolve_hash_algo(hash_algo=None)[source]
The HashAlgo a writer declares AND hashes with.
Explicit hash_algo wins, then
default_hash_algo(), then BLAKE3 (spec default) when theblake3package is importable, else SHA-256. The declared algorithm is never silently substituted: an explicit BLAKE3 withoutblake3raisesHashAlgoUnavailable.
- class CapBit[source]
Bases:
object- MEMORY_REGIONS = 1
- MODULE_LIST = 2
- THREAD_CONTEXTS = 4
- FILE_DESCRIPTORS = 8
- NETWORK_STATE = 16
- ENVIRONMENT_VARS = 32
- SHARED_MEMORY = 64
- SECURITY_CONTEXT = 128
- PROCESS_IDENTITY = 256
- RELATED_DUMPS = 512
- CRYPTO_HINTS = 1024
- SYSTEM_CONTEXT = 2048
- SYSTEM_PROCESS_TABLE = 4096
- SYSTEM_NETWORK_TABLE = 8192
- SYSTEM_HANDLE_TABLE = 16384
- PAGE_STATES_INFERRED = 32768
- class ModuleEntrySpec[source]
Bases:
objectOne module record for add_module_list_index().
The writer assigns any missing module UUID when the record is added. The Module List Index records the same UUID as the Module Entry block. The entry names the index as its parent.
- class ProcessTableEntry[source]
Bases:
objectProcessTableEntry(pid: int, ppid: int = 0, uid: int = 0, is_target: bool = False, start_time_ns: int = 0, rss: int = 0, exe_name: str = ‘’, cmd_line: str = ‘’, user: str = ‘’)
- class ConnectionTableEntry[source]
Bases:
objectConnectionTableEntry(pid: int = 0, family: int = 0, protocol: int = 0, state: int = 0, local_addr: bytes = b’’, local_port: int = 0, remote_addr: bytes = b’’, remote_port: int = 0)
- class HandleTableEntry[source]
Bases:
objectHandleTableEntry(pid: int, fd: int, handle_type: int = 0, path: str = ‘’)
- class ExtensionBlock[source]
Bases:
objectOne block of an extension segment (spec 4.6) for
MslWriter.add_extension_segment().payloadis the on-disk payload (already compressed whenflagssays so);block_uuid/parent_uuiddefault to a fresh uuid4 / zero. Used by materialize to re-emit a verified source segment with its block identities intact.
- class MslEncryptionConfig[source]
Bases:
objectProducer-side AEAD encryption configuration (spec §10).
Pass to
MslWriter(encryption=...)to emit an encrypted container. Provide exactly one form of key material matching the chosenkey_encap/kdf_type:key_encap=NONE, kdf_type=NONE -> raw_key (32 bytes)
key_encap=NONE, kdf_type=ARGON2ID -> passphrase
key_encap!=NONE -> recipient_public
nonce and kdf_salt are normally generated from a CSPRNG; supply them only for deterministic fixtures/tests.
Re-wrap mode (
rewrap()): a derived copy of a decrypted container reuses its content key and key wrapping (rewrap_material) so the same key / passphrase / private key opens the copy; the nonce is always fresh and the source nonce is refused.- classmethod rewrap(material)[source]
Config that re-encrypts under material’s key wrapping (fresh nonce).
- Parameters:
material (RewrapMaterial)
- Return type:
- __init__(enc_algo=EncAlgo.AES_256_GCM, kdf_type=KdfType.NONE, key_encap=KeyEncap.NONE, raw_key=None, passphrase=None, recipient_public=None, kdf_time=3, kdf_memory=65536, kdf_lanes=4, nonce=None, kdf_salt=None, rewrap_material=None)
- Parameters:
- Return type:
None
- class MslWriter[source]
Bases:
objectQueue capture blocks and write the file in section 6.1 order.
Place Import Provenance first for an import, or Process Identity first for a live capture, when the corresponding record is present. An imported Process Identity follows provenance when requested. Write the module index and its entries next. In investigation mode, write System Context and its tables after the modules.
Other blocks follow the order in which they were added. Add thread contexts before memory regions. End of Capture closes the capture segment. Registered extension segments follow it.
- __init__(path, pid=0, os_type=OSType.UNKNOWN, arch_type=ArchType.UNKNOWN, imported=True, investigation=False, encryption=None, region_block_cap=REGION_BLOCK_CAP, dump_uuid=None, timestamp_ns=None, clock_source=0, hash_algo=None)[source]
Set the output path and the metadata for a new capture.
The defaults use a new version 4 UUID, the write time, and clock source 0. To preserve the identity of an existing capture, supply its dump_uuid, timestamp_ns, and clock_source.
hash_algo selects the algorithm for the integrity chain and file and segment hashes. See
resolve_hash_algo()for the default. Supply Module Entry DiskHash values that use the same algorithm.
- add_memory_region(base_addr, data, protection=0x03, region_type=0x05, page_size_log2=12, timestamp_ns=0, page_states=None, compression=CompAlgo.NONE)[source]
Add a region and return the UUID of its first block.
Pass one page_states entry for each virtual page. Pass only the captured pages in data, in page order. When page_states is omitted, all pages are captured. The page size is 2 to the power of page_size_log2, which must be between 10 and 40.
The block cap can split a region on page boundaries. Optional compression applies to each block. The integrity chain covers the encoded bytes stored in the file.
- add_memory_region_source(base_addr, region_size, read_chunk, protection=0x03, region_type=0x05, page_size_log2=12, timestamp_ns=0, page_states=None, compression=CompAlgo.NONE)[source]
Register a region whose bytes are read during writing.
region_size must be a multiple of the page size. If supplied, page_states has one entry per virtual page. The callback read_chunk takes an offset and length in bytes. It must return exactly that many bytes from the captured pages in page order.
Compression is unavailable for streamed regions. The output can be encrypted. Return the UUID of the first region block.
- region_for_va(va)[source]
Return (block_uuid, offset_in_block) of the region block holding va.
Resolves to the specific chunk block of a split region, so key hints built from the result reference the block that contains the bytes. Returns None when no registered region covers va.
- add_key_hint(region_uuid, offset, key_length, key_type, protocol, confidence=0x01, key_state=0, note='')[source]
Add a key hint block (spec §5.6) referencing a memory region.
When region_uuid names a region that was split into several blocks, (region_uuid, offset) is remapped to the chunk block that holds offset and the offset is rebased onto that chunk.
- add_import_provenance(source_format, tool_name, orig_file_size, note='', source_path=None)[source]
Add an Import Provenance block (spec §11).
For imported=True files, this block is emitted as Block 0.
When source_path is provided and readable, its BLAKE3 digest is computed and written as source_hash. An omitted or missing file yields 32 zero bytes. Other file errors propagate.
Add a Related Dump block (spec §5.5, type 0x0041).
When target_path is provided and readable, its BLAKE3 digest is computed and written as target_hash, pinning the cross-reference. An omitted or missing file yields 32 zero bytes. Other file errors propagate.
- add_process_identity(ppid=0, session_id=0, start_time_ns=0, exe_path='', cmd_line='', emit_when_imported=False)[source]
Add a Process Identity block (spec §5.4, type 0x0040).
For imported=False (live) acquisitions, this is emitted as Block 0. An imported file drops it unless emit_when_imported is set; then it is emitted right after Import Provenance (Block 1).
- add_module_list_index(modules)[source]
Add a Module List Index (spec §5.3, type 0x0010) plus one Module Entry block (spec §5.2, type 0x0002) per module as children.
The index is emitted as Block 1 (immediately after Block 0). Each Module Entry’s block_uuid matches the pre-assigned ModuleUUID recorded in the index, and its parent_uuid references the index. Implements the spec’s Variant A (inline entries).
- Parameters:
modules (Sequence[ModuleEntrySpec])
- Return type:
- add_thread_context(thread_id, registers, *, flags, state=ThreadState.STOPPED, arch=0, name='', start_time=0, parent_uuid=None)[source]
Queue a Thread Context block (spec §5.7, type 0x0011).
flags carries the
TC_FLAG_*bits, state aThreadStatecode (default Stopped: a core / minidump thread is a stopped snapshot) and arch 0 for “same as the header ArchType”. Register names are written lowercase. The block lands in call order among the generic blocks, so call this before the firstadd_memory_region*(spec: SHOULD precede the first Memory Region). parent_uuid may name the Process Identity block.Raises
ValueErroron an empty / over-long register name, a width outside 1..255, a value not exactly width bytes, or a state / arch that does not fit u8.
- add_raw_block(block_type, payload, block_uuid=None, parent_uuid=None, flags=0)[source]
Queue an opaque block (already-encoded payload) in call order.
For copying blocks from an existing
.mslwithout re-decoding them: payload is written as-is (it must already be compressed when flags carries BlockFlag.COMPRESSED), and passing the source’s block_uuid / parent_uuid keeps parent references between copied blocks valid. The caller is responsible for the capability bitmap (see add_capabilities()).
- add_capabilities(bits)[source]
OR bits into the capability bitmap (for add_raw_block content).
- Parameters:
bits (int)
- Return type:
None
- add_raw_appendix(encoded)[source]
Deprecated: unchained post-EoC appendices no longer exist.
Spec 1.1 (Section 4.6) replaced the appendix with extension segments: blocks after EoC are chained, counted and closed by an End-of-Extension block. Re-emit the blocks through
add_extension_segment()instead (materialize does this for verified source segments).- Parameters:
encoded (bytes)
- Return type:
None
- add_extension_segment(producer, blocks, written_at_ns=None)[source]
Register an extension segment (spec 4.6) to be emitted after EoC.
blocks (at least one) are written in order after the End-of-Capture block and every earlier segment, then closed by an End-of-Extension block carrying
SegmentHash, the exactBlockCount(blocks + terminator) and producer (None=memdiver/<version>). written_at_ns sets the terminator’sWrittenAt(None= this writer’s own timestamp); materialize keeps a source segment’s value. Block types the spec forbids in extension segments (evidence: 0x0001, 0x0002, 0x0010-0x0015, 0x0030, 0x0040, 0x0050-0x0058, 0x0FFF) and the terminator itself are rejected.Returns the segment’s index (emission order).
write()requires an End-of-Capture block once any segment is registered.- Parameters:
producer (str | None)
blocks (Sequence[ExtensionBlock])
written_at_ns (int | None)
- Return type:
- property extension_segment_count: int
Segments registered so far (emitted in this order after EoC).
- add_vas_map(entries)[source]
Add a VAS Map block (type 0x1001): the address-space layout overlay.
Payload (mirrors
decoders.decode_vas_map):u32 entry_count,u32 entry_size(0 = variable-length entries), then per entryu64 base_addr, u64 region_size, u8 protection, u8 region_type, u16 path_len(raw length incl. NUL, 0 when no path),u8 name_source(VasNameSource), 3 reserved bytes, and the NUL-terminated path padded to 8 bytes. The format has no “captured” flag: a VAS entry without a matching MEMORY_REGION block is a range whose bytes were not stored.
- add_system_context(boot_time_ns, target_count, acq_user, hostname, domain='', os_detail='', case_ref='')[source]
Add a System Context block (spec §6.2, type 0x0050).
Emitted as Block 2 when investigation=True. Sets HeaderFlag. INVESTIGATION in the file header and CapBit.SYSTEM_CONTEXT in the capability bitmap (both required by spec §9 when Investigation=1).
TableBitmap is populated automatically based on which add_*_table methods are subsequently called.
- add_process_table(entries)[source]
Add a Process Table block (spec §6.3, type 0x0051).
ParentUUID references the System Context block (mandatory).
- Parameters:
entries (Sequence[ProcessTableEntry])
- Return type:
- add_connection_table(entries)[source]
Add a Connection Table block (spec §6.4, type 0x0052).
Spec §6.4 mandates that ports be stored little-endian in the block — callers MUST convert from network byte order before passing entries to this method.
- Parameters:
entries (Sequence[ConnectionTableEntry])
- Return type:
- add_handle_table(entries)[source]
Add a Handle Table block (spec §6.5, type 0x0053).
- Parameters:
entries (Sequence[HandleTableEntry])
- Return type:
- add_pointer_graph(nodes, edges, emit_integrity=True, producer=None)[source]
Register a POINTER_GRAPH block in its own extension segment.
POINTER_GRAPH (0x1003) is a producer-defined Structural block, so the spec (4.6) admits it only in an extension segment: it is written after the End-of-Capture block, chained from it (zero PrevHash inside an encrypted container) and closed by an End-of-Extension block. The user opts in by calling this method; readers that do not implement extension segments stop at EoC and ignore it.
When emit_integrity is True (default), the payload is followed by a 32-byte BLAKE3 trailer over (header + nodes + edges). The reader surfaces the stored hash on MslPointerGraph.appendix_hash; callers may use
decoders_ext.verify_pointer_graph_integrityto re-check it (the segment’s SegmentHash covers the block as well).Returns the block’s UUID. Calling twice replaces the writer’s own pointer-graph segment (segments added through
add_extension_segment()are untouched).
Register a share-class block in its own extension segment (spec 4.6).
The block (type
share_classes.BLOCK_TYPE, payload taggedmemdiver.shareclass/1) is a producer-defined Structural block: derived data, so the spec admits it only after the End-of-Capture block; the capture segment is untouched and the segment carries its own SegmentHash. Returns the block’s UUID.
- add_connectivity_table(rows)[source]
Add a Connectivity Table block (spec §6.6, type 0x0055).
System-wide connectivity snapshot — routes, ARP, packet sockets, interface stats, socket-family aggregates, MIB counters. Unlike the per-process tables under System Context, this is a top-level block; spec has not yet assigned a CapBit, so the bitmap is left untouched (SYSTEM_NETWORK_TABLE is for the per-process CONNECTION_TABLE 0x0052, a distinct concept).
- add_physical_memory_map(rows)[source]
Add a Physical Memory Map block (spec 5.9, type 0x0059, v1.1).
Host physical address ranges (
/proc/iomemtop level) at acquisition time. Optional, ParentUUID zero. Files using it already carry Version 0x0101 (the writer’s only version).
- add_end_of_capture(reason=0, acq_end_ns=None)[source]
Add an End-of-Capture block (spec §4.5).
The 32-byte file_hash slot is left as zeros here; write() finalizes it with a digest covering the file header and every preceding encoded block, and fills in the block count (the 40-byte stub grows to the 48-byte EoC payload). acq_end_ns defaults to now.
- write()[source]
Write the queued capture and extension blocks to the output file.
Finalize the End of Capture digest and count. The digest covers the encoded capture before that block. For encrypted files it follows the specification’s plaintext hash rules.
Use the streaming path when a region reads its data from a registered source.
- Return type:
None
- write_streaming()[source]
Write the file block-by-block with O(chunk) peak memory.
Produces the same layout as the plaintext write() path: header with the exact pre-computed BlockCount and CapBitmap, HashAlgo-chained blocks, EoC FileHash over header + every prior block, then the registered extension segments. The prev_hash chain and EoC hasher are updated incrementally while bytes are written, and streamed region bytes are pulled in STREAM_CHUNK_SIZE pieces. Writes to a temp file and calls
os.replaceon it on success, like write().Encrypted writers stream too (
_write_streaming_encrypted()): the output is byte-identical to the in-memory encrypted write() for the same nonce.- Return type:
None
- build_import_provenance_payload(source_format, tool_name, orig_file_size, note='', source_path=None)[source]
Encode an IMPORT_PROVENANCE payload (spec §11).
Shared by add_import_provenance() and callers that place the block themselves via add_raw_block().
Import process captures into Memory Slice files.
Preserve the source metadata and the page states that the importer can establish. A filtered rewrite records which regions it excluded.
- class ImportResult[source]
Bases:
objectDescribe the output from importing or rewriting one process capture.
Report region and key-hint counts along with selection warnings. A materialized result also reports changes to the output’s encryption.
- __init__(source_path, output_path, regions_written, key_hints_written, total_bytes, selection=None, excluded_region_count=0, excluded_bytes=0, secrets_only_in_excluded=0, warnings=<factory>, materialized=False, dropped_key_hints=0, reencrypted=False, decrypted_output=False)
- Parameters:
- Return type:
None
- import_elf_core(elf_path, output_path, secrets=None, page_size_log2=None, selection=None)[source]
Convert an ELF process core into a Memory Slice capture.
Keep separate regions for the load segments that the selection includes. A region can span more than one block if it exceeds the writer’s block cap. Record stored pages as captured and remaining virtual pages as failed. Use available NT_FILE mappings to build the module index.
Record the full layout and available mapping names in the VAS map, including regions that the selection excludes.
- Parameters:
- Return type:
- class RegionSpec[source]
Bases:
objectOne assembled MSL memory region derived from a minidump.
dataholds exactly the CAPTURED page bytes (FAILED/UNMAPPED pages contribute zero bytes), solen(data) == captured * page_size.
- class StreamedRegionSpec[source]
Bases:
objectStreaming twin of
RegionSpec: CAPTURED bytes as file runs.runsdescribe the CAPTURED byte stream (file ranges, zero fill and small literal edge pages) over the mapped minidump, so the region is never materialised;data_len == captured * page_size.
- import_minidump(dmp_path, output_path, pid=0, secrets=None, page_size_log2=12, selection=None)[source]
Convert a Windows minidump to Memory Slice.
Use the committed memory ranges when the minidump contains a memory information list. A page with bytes in a memory descriptor is
CAPTURED. A mapped page without bytes isFAILED. When no memory information list is present, use the descriptors as captured regions.Pass selection to retain only the included regions. The output records the page states as inferred and preserves available module and thread metadata.
- import_raw_dump(raw_path, output_path, pid=0, secrets=None, os_type=OSType.UNKNOWN, arch_type=ArchType.UNKNOWN, page_size_log2=12, selection=None)[source]
Convert a raw .dump file to .msl format.
A raw dump is one UNCLASSIFIED region, so a selection either keeps it or (keeping 0 bytes) falls back to importing it with a warning; it is recorded in provenance either way. The stored region type is unchanged.
Streams: the source is mmapped read-only and registered with
MslWriter.add_memory_region_source, so peak RAM is bounded by the writer’s stream chunk, not the dump size.
- import_regioned_raw(bin_path, maps_path, output_path, pid=0, secrets=None, selection=None, arch_type=ArchType.UNKNOWN)[source]
Convert a flat
.bin+/proc/<pid>/mapssidecar into an .msl.One MEMORY_REGION per maps entry at its real VA, typed from the entry’s path (
[heap]-> HEAP,[stack]-> STACK, libraries -> IMAGE, …) and protected from itspermcolumn; a truncated last entry keeps its listed size with the missing pages FAILED. File-backed entries become a Module List Index. Streams throughRunSource(bounded RAM). Every entry’s full path column is kept as its mapping name in an always-written VAS_MAP (region_names=1in provenance); the headeros_typeis ANDROID when the names carry Android markers.When the sidecar does not describe the bin exactly (see
msl.import_regioned.plan_regions()) the dump is imported as one plain raw region instead, with a warning on the result.
- import_msl_passthrough(src_path, output_path, selection=None, materialize=False, key_material=None, decrypt_output=False)[source]
Stage an MSL file or write a region-filtered copy.
The default checks the source header and copies the file byte for byte. A locked container can be staged, with region and key-hint counts unavailable. If a selection accompanies a verbatim copy, the result records the selection and warns that the file still holds all regions.
Set materialize with a selection that excludes regions to write a filtered file. The writer preserves capture identity, rebuilds the virtual address map, and remaps or drops key hints. An encrypted source needs valid key_material for this operation.
The encrypted copy uses the same key wrapping with a fresh nonce. Set decrypt_output to write plaintext. A verbatim copy retains its original encryption and reports that the flag was ignored.
- RUN_META_MAPS_KEY = 'maps'
Optional run
meta.jsonkey naming a .maps file (run-dir relative).
- run_directory_declared_maps(run_dir)[source]
The
mapsfile a run’smeta.jsondeclares, if it exists.Resolved through
core.dataset_metadata.resolve_declared_subpath(), so an absolute or escaping declaration is rejected (logged, ignored).
- run_directory_dump_files(run_dir)[source]
The dump files
import_run_directory()imports, in import order..dump/.dmp/.core, gdb_raw / lldb_raw.binfiles, and any other.binthat has a.mapssidecar (or ameta.jsonmapsdeclaration).
- run_directory_maps_for(run_dir, dump_file)[source]
Explicit maps
import_run_directory()passes for dump_file.The run
meta.jsonmapsdeclaration, for a raw file without its own sidecar (a sidecar is auto-detected byimport_dump()anyway).
- import_run_directory(run_dir, output_dir, keylog_filename='keylog.csv', selection=None, materialize=False, key_material=None, decrypt_output=False)[source]
Import all dump files in a run directory to .msl.
See
run_directory_dump_files()for which files count; raw files with a.mapssidecar (or the runmeta.jsonmapskey) are split into real regions.Each file is routed through
import_dump(), which sniffs the format and dispatches to the raw, ELF-core, or minidump importer as appropriate. materialize, key_material and decrypt_output only affect.mslinputs (see import_msl_passthrough); one key material is tried for every.mslin the run.
- import_dump(src_path, output_path, pid=0, secrets=None, selection=None, materialize=False, key_material=None, decrypt_output=False, maps_path=None, **kwargs)[source]
Detect the source format and import a process capture into MSL.
Convert Windows minidumps and ELF process cores directly. An ELF core that cannot be parsed falls back to raw import. For raw bytes, supply maps_path or place a matching
.mapsfile next to the dump to preserve its region boundaries. Formats with their own layout ignore the supplied map and report a warning.Pass selection to restrict a conversion to included regions. An MSL source is copied byte for byte by default. Set materialize to write a selected copy. For encrypted MSL input, supply the applicable key_material. Use decrypt_output to write a materialized copy as plaintext.