Expand description
§odx-rs
A parser for ASAM MCD-2 D (ODX) diagnostic descriptions and the PDX containers that carry them, written in Rust.
ODX describes how a diagnostic tester talks to an ECU: the services it offers,
the byte layout of every request and response, the meaning of each value and
the trouble codes it can report. A .pdx file is a ZIP archive of those XML
documents. odx-rs opens the archive, reads the documents and hands back one
navigable model.
The crate is plain Rust with no platform assumptions — it powers a browser viewer through WebAssembly, and works just as well in a command line tool.
§Install
[dependencies]
odx-rs = "0.39"§0.39.0
- Six new Annex B rules over the flash data model — ordered address ranges
(B.71–B.74), one
TYPEperEXPECTED-IDENT(B.69), and typed flash values that parse as what they declare (B.75) — taking the audited profile to 56 numbered rules. - The rule table below is complete again: it had drifted 19 rules behind the
implementation, and now carries one row per identifier
validation_rule_ids()reports.
§0.38.0
- The workspace viewer uses
inspect_pdxto show the model and validation findings from one parse, with a Validation tab and status counts. - The two-pane viewer now remains operable without horizontal overflow at a 303 px viewport.
No library parsing or validation behaviour changed.
§0.37.0
odx rulesexposes the validation inventory as newline-delimited text or a 63-item JSON array, without requiring a container.- Corrected the conformance record to identify the three numbered warning rules rather than describing all 50 as errors.
§0.36.0
validation_rule_ids()exposes the complete validation-profile inventory; the WebAssembly module exports the same list for browser consumers.- The viewer displays the inventory supplied by its bundled core instead of a copied count.
- The production viewer build now uses the size-optimised
wasm-releaseprofile and stays inside the project’s 650 KB module budget.
§0.27.0–0.35.0
These releases expanded the audited Annex B profile to 50 numbered rules, corrected B.50 and B.223 edge cases, measured the coverage denominator, and reconstructed missing registry history and source provenance. The complete per-version record is the registry-audited CHANGELOG, including the two tagged versions that were never published.
§0.26.0
- New rule
B.139: aLOGICAL-LINKnames one of the four layer combinations the clause enumerates, and each reference resolves to the kind it names — aBASE-VARIANT-REFpointing at anECU-VARIANTselects the wrong layer on the vehicle. - New rule
C.SDG-CAPTION-ID: anSDG-CAPTIONwithout the identifier Annex C makes mandatory. The reference implementation refuses to load such a file while this reader reported it clean. OdxService::audiencekeeps a stated denial apart from silence. ODX defaults an omittedIS-…to true, soIS-SUPPLIER="false"denies while omitting grants — reading only the"true"flags inverted that, and lost 64 stated denials in the committed fixture alone.- A byte layout the parse bounds cut short says so, with a
ROWS-TRUNCATEDorDEPTH-TRUNCATEDrow. It used to stop silently, so “nothing more” and “not shown” looked identical. No real container produces either marker. - A
deserializefeature reads the model back from its own JSON, so a parse result can be archived and a stored baseline diffed against a fresh container. Off by default; the WebAssembly module is byte-identical without it.
§0.25.0
B.38fires when aDTC-DOPstates no physical type at all. The clause says the base type “shall be set”; comparing only a stated value let the document furthest from conformant pass.B.51follows §7.3.5: a parameter without aBYTE-POSITIONis packed at the byte edge after the previous one, not placed at byte 0 — which reported the layout the clause describes as correct.
§0.24.0
- Annex B rule 156: a
STRUCTURE’s statedBYTE-SIZEmust cover its parameters, and must be absent where the structure has a component whose length is decided at run time. A size stated there contradicts the data, and a decoder that trusts it misplaces everything after the structure. tests/hostile_shapes.rspins that reference cycles, self- and mutually-inheriting layers and dangling references all terminate — one of them on the 1 MiB stack the browser build gets.
§0.23.0
-
Lists a
MUX,STATIC-FIELD,END-OF-PDU-FIELDorDYNAMIC-LENGTH-FIELDthat no parameter references. These were collected only where a parameter pointed at one — which covers every use, and not a definition standing on its own, which a dictionary is allowed to hold. Counts move: the demo fixture goes from 12 DOPs to 14.Found by the first foreign container this crate has been run against (odxtools’
somersault.pdx), which defines one multiplexer and references it nowhere.
§0.22.0
OdxParam::dop_kindsays what a parameter’sDOP-REFpoints at. ADOP-REFmay name anyDOP-BASEwhiledocument.dopsholdsDATA-OBJECT-PROPalone, so joining the two found nothing for a structure, mux or field — and could not tell that from a dangling reference.
§0.21.0
- Seven Annex C grammar rules: identifiers only where the schema declares
them,
NRC-CONST’s mandatoryCODED-VALUESwrapper, a comparam’s requiredCPUSAGE, the data dictionary’s declared child order, the parameter that selects a snapshot’s trouble code, and a vehicle link’s pins. The schema states each; a reader that does not run the schema accepts the file and the next tool in the chain rejects it. Two ship as warnings — see the CHANGELOG for why. These can flip a previously-clean archive to exit 1.
§0.20.0
inspectreturns the model and the findings from one read of the container — measured 23-27% faster than callingparsethenvalidate, which each inflate the archive and parse every document in it. Both existing functions are unchanged; a test asserts the answers are identical.
§0.19.0
- New rule
NRC-CONST-SET, error level: a negative response’s codes belong to oneNRC-CONST(ISO 22901-1 §7.3.6.10, andCODED-VALUEismaxOccurs="unbounded"), not to one parameter per code. Several of them on one byte each demand the byte hold their own value, so the message matches nothing. This can flip a previously-clean archive to exit 1. - New warning: a package holding no ODX document at all.
0 error(s), 0 warning(s)on an archive with nothing in it read exactly like a clean verdict, which is the answer a caller acts on. OdxParam::coded_valuesgives every code a parameter accepts as numbers, so reading anNRC-CONST’s set no longer means parsing the"0x13, 0x31"display string.odx tree --format jsonprints the model as data — short names, parameter positions, coded values — instead of accepting the flag and printing the indented list anyway.treeandsummarynow reject--format sarif.- Every public model type implements
Clone.
§0.18.0
- Reads loose ODX documents without a PDX around them, via
parse_documents/validate_documentsandodx validate <dir>. Both take a document set, since a layer’s references into the subset beside it are ordinary and only resolve when the documents that travel together are supplied.
§0.17.0
- The public model types are
#[non_exhaustive], so the field additions this crate makes every release stop being source-breaking. Reading is unchanged; constructing one needs..Default::default(). - A skipped archive entry reports why — damaged, over the per-document limit, or over what the archive budget had left.
§0.16.0
- Adds
OdxDocument::services: every service each layer offers, with its numeric identifier, references, functional classes and precondition states — and the layer that declared it, so “what does this variant answer to” and “how many services exist” stay separable.
§0.15.1
- Security. Refuses a document nested deeper than 256 elements. Recursive
passes over the parsed tree overflowed the stack on deeply nested input and
aborted the process — from a 400-byte archive on the browser’s 1 MiB stack,
where
panic = "abort"takes the page with it. The 0.14.0 size bounds do not cover this: such a document is a few kilobytes. Real ODX nests 14 deep.
§0.15.0
- Adds a fixture generated by an independent producer (udsdoc) with tests pinning the invariant that this reader reports nothing on real-world output — previously checked only by a CI job needing network and Python.
§0.14.1
- Restores the release notes for 0.12.0-0.14.0, which had been lost from this file, and documents the machine-readable indexes and the input bounds in the body rather than only in the changelog.
§0.14.0
- Bounds what is inflated from an archive: 64 MiB per document, 256 MiB per archive, 65,536 entries, and no pre-allocation on the header’s unverified say-so. The reader takes arbitrary uploads in the browser, where an allocation failure aborts the page — a crafted archive under 1 MB could previously drive a 4.6 exabyte allocation. An oversized document is reported as skipped rather than silently dropped.
§0.13.0
OdxDopgainsphysical_base_data_type,coded_type_kindandhigh_low_byte_order— the facts a decoder needs beyond the bit length, with the byte order reported as its effective value rather than as written.
§0.12.0
- Adds
OdxDocument::dtcs(trouble codes as data, with numeric codes),OdxDocument::summary(the countsparser_inforenders, as numbers), andOdxParam::kind/OdxParam::coded_value, so a program no longer has to parse display strings whose format is a presentation choice. - Builds the browser module with a
wasm-releaseprofile that is 13.4% smaller thanrelease, without slowing theodxcommand.
§0.11.0
- Reads communication-parameter overrides attached directly to a diagnostic
service, resolving the referenced ODX-CS definition and preserving its
ODX 2.2
SIMPLE-VALUEin the service tree. LegacyVALUEinput remains readable.
§0.10.0
- Ships an installable
odxcommand (cargo install odx-rs) withvalidate,tree,summaryanddops, text/JSON/SARIF output, and an exit-code contract a CI job can gate on. See “Theodxcommand” below. - Adds a
clifeature (default on) so the library and the WebAssembly build do not carry the command’sserde_jsondependency. - Declares an MSRV of 1.88 and starts a CHANGELOG.
§0.9.0
- Reads
ENV-DATA-DESCthrough theENV-DATA-REFSlist the ISO schema makes mandatory, so the snapshot records kept with a trouble code are reachable. An inlineENV-DATASwrapper is still accepted. - Reads
ECU-VARIANT-PATTERN/BASE-VARIANT-PATTERN: which diagnostic communication to run, which output parameter to read and the value it must match. This is how a tester picks the variant in front of it, and it was invisible. - Reads the
PROT-STACKs of aCOMPARAM-SPEC— the PDU protocol and physical link type aPROTOCOLlayer’s communication parameters are meant for. OdxDopcarriesinverse_scalesfromCOMPU-PHYS-TO-INTERNAL, the conversion back from a physical value to the coded one that an encoder needs.
§0.8.0
- Reads a
COMPLEX-COMPARAM’s members. The ISO schema nests them directly under it as an unbounded choice ofCOMPARAMandCOMPLEX-COMPARAM, with no wrapper; looking only inside aCOMPARAMSwrapper found none of them. Its positionalCOMPLEX-PHYSICAL-DEFAULT-VALUEis reported too. - Reads the
UNIT-SPEC: each unit with itsFACTOR-SI-TO-UNIT,OFFSET-SI-TO-UNITand physical dimension, and eachPHYSICAL-DIMENSIONwith its SI exponents. Resolving aUNIT-REFto a display name loses the conversion, which exists nowhere else in the container.
§0.7.0
- Reads the vehicle-information topology: the
INFO-COMPONENTs that identify the vehicle (manufacturer, model, model year, VIN) with the value a tester is expected to match, theVEHICLE-CONNECTORs and their pins, thePHYSICAL-VEHICLE-LINKs with the protocol each carries, and whether a logical link reaches its ECU directly or through a gateway. - Reads
ADMIN-DATAwherever it appears — language, company and theDOC-REVISIONtrail (label, state, date, tool) — so a delivery says who produced it and at what revision. - Reads a flash session’s
SECURITY-METHODand a segment’sSOURCE-END-ADDRESS, which together say how the ECU is unlocked and where the memory range ends. - Reads the bounds and
TERMINATIONof aMIN-MAX-LENGTH-TYPE, so a variable-length payload no longer reads back as a zero-bit row. OdxCompuScalecarries the numericCOMPU-CONST/Vand the scale’sSHORT-LABELbeside the textual constant it already had.- Names the request byte a
MATCHING-REQUEST-PARAMechoes, and reports a service’sIS-EXECUTABLE.
§0.6.0
- Reads
TABLE-ROWwritten directly underTABLE, the shape ODX 2.2.0 specifies, as well as theTABLE-ROWSwrapper some producers emit. - Reads the response codes of an
NRC-CONSTparameter from the mandatoryCODED-VALUESlist, so negative responses no longer read back without their codes. A parameter offering several codes shows all of them. - Surfaces a layer’s
GLOBAL-NEG-RESPONSES— the ECU-wide negative-response catalogue, which no service references and which was therefore invisible. - Adds an
inspectexample that reports what a container read back as, per node kind, for spotting constructs a producer writes but the reader drops.
§0.5.2
- Corrects B.11 to read
PHYSICAL-TYPE/PRECISIONas a child element and report it on non-floating-point physical types. - Exposes schema-correct
PRECISIONandDISPLAY-RADIXvalues in the viewer model and corrects the demo PDX fixture.
§0.5.1
- Makes parser and validator reference resolution consistently document-aware.
- Corrects imported DOP short-name precedence, zero bit lengths, shared DOP-BASE inheritance namespaces, and deep parent chains.
- Removes the fixed sniff window for misnamed ODX members.
§0.5.0
- Resolves ODX links by document,
DOCREF,DOCTYPE, and effective layer data pool instead of package-global bare IDs. - Hardens B.31, B.50, B.51, B.107, B.165, B.172, B.185, B.186, and B.223 with adversarial cross-document, inheritance, field-layout, and schema-default cases.
- Aligns catalogue handling with Annex C cardinalities/defaults and all four
incremental omission states, including
REUSED. - Parses supported declared XML encodings and rejects additional well-formedness errors.
- Defines the partial-profile boundary in CONFORMANCE.md.
§0.4.0
- Adds PDX catalogue structure and incremental-exchange validation, ODX
category-extension, contextual
DOCREF, and diagnostic-layer inheritance validation. - Expands the Annex B validation profile to 31 rules, including B.11, B.12, B.15, B.31, B.50, B.107, B.158, B.165, B.172, B.186, B.213, B.223, and B.227.
- Audits all 31 implementations against the normative Annex B table, including effective layer data pools, bounded variable request fields, referenced and linked DTC sets, and complex communication-parameter values.
- Rejects malformed XML roots and non-UTF-8 ODX documents during validation.
- Preserves all SDG rows by default; presentation limits are now opt-in.
§Usage
use odx_rs::OdxNode;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let bytes = std::fs::read("DemoVehicle_Diagnostics.pdx")?;
let document = odx_rs::parse(&bytes, "DemoVehicle_Diagnostics.pdx")?;
println!("{} ({})", document.file_name, document.parser_info);
for root in &document.roots {
print_node(root, 0);
}
Ok(())
}
fn print_node(node: &OdxNode, depth: usize) {
println!("{:width$}{} [{:?}]", "", node.name, node.kind, width = depth * 2);
for child in &node.children {
print_node(child, depth + 1);
}
}Every node carries the ODX identifiers and attributes it came from, so what you display can be traced back to the source document:
use odx_rs::{OdxNode, OdxNodeKind};
/// Collects every diagnostic service, labelled with its service identifier.
fn services(node: &OdxNode, out: &mut Vec<String>) {
if node.kind == OdxNodeKind::Service {
// `badge` holds the service identifier, e.g. "0x22".
let id = node.badge.as_deref().unwrap_or("--");
out.push(format!("{id} {}", node.name));
}
for child in &node.children {
services(child, out);
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let bytes = std::fs::read("container.pdx")?;
let document = odx_rs::parse(&bytes, "container.pdx")?;
let mut found = Vec::new();
for root in &document.roots {
services(root, &mut found);
}
println!("{} services", found.len());
Ok(())
}Failures say what went wrong, so a malformed upload can be told apart from a bug:
use odx_rs::ErrorKind;
let bytes = b"<?xml version=\"1.0\"?>";
match odx_rs::parse(bytes, "maybe.pdx") {
Ok(document) => println!("{} roots", document.roots.len()),
Err(error) => match error.kind() {
ErrorKind::NotAContainer => eprintln!("not a PDX file: {error}"),
ErrorKind::UnreadableArchive => eprintln!("damaged archive: {error}"),
},
}A document inside the archive that fails to parse does not fail the call:
it is collected under a Problems node and counted in parser_info, so a
partly broken container still shows everything that could be read.
§Checking a container
Reading a container and judging it are separate questions: parse is
deliberately forgiving, while validate applies the crate’s audited, partial
ISO 22901-1:2008 ODX/PDX validation profile. It reports malformed XML, selected
PDX catalogue/schema conditions, invalid cross-document links, and the Annex B
violations listed below:
use odx_rs::Severity;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let bytes = std::fs::read("container.pdx")?;
for finding in odx_rs::validate(&bytes, "container.pdx")? {
let mark = match finding.severity {
Severity::Error => "error",
Severity::Warning => "warn ",
};
println!("{mark} {} {} — {}", finding.rule, finding.location, finding.message);
}
Ok(())
}Every finding carries the path it was found at, so a report can be checked against the source document by hand.
The rules with a B. number come from Annex B of ISO 22901-1; the C. rules
enforce declarations of the Annex C schema this reader deliberately does not
run; the rest are named after what they check. This table is complete — one
row per identifier validation_rule_ids() reports:
| Rule | What it requires |
|---|---|
B.5 | A PROG-CODE’s SYNTAX is one of the strings the standard matches against (warning — the clause says “is matched against”, not “shall be one of”) |
B.11 | DISPLAY-RADIX and PRECISION fit the physical data type |
B.12 | MIN-LENGTH does not exceed MAX-LENGTH |
B.14 | SCALE-CONSTR ranges do not overlap one another |
B.15 | End-of-PDU minimum item count does not exceed its maximum |
B.16 | A CASE’s LOWER-LIMIT does not exceed its UPPER-LIMIT |
B.17 | An item-count DATA-OBJECT-PROP converts to A_UINT32 |
B.31 | Each ID-REF resolves through its stated document context to a target in the current layer data pool |
B.38 | A DTC-DOP states A_UINT32 as its physical base type — absent counts as a violation, not a pass |
B.41 | A message carries at most one SERVICE-ID parameter |
B.42 | Byte and string coded types declare no byte order, except for a leading-length field |
B.43 | INTERNAL-CONSTR uses an ordered coded type |
B.44 | A SWITCH-KEY’s DOP has a STANDARD-LENGTH-TYPE, so its width is knowable before the case it selects |
B.46 | A MUX without CASES has a DEFAULT-CASE |
B.50 | Diagnostic-layer parent relationships follow the ODX hierarchy |
B.51 | Parameters of one request must not claim the same bits — unpositioned parameters follow the §7.3.5 packing rule, and bounded variable-length fields count |
B.52 | A TAB-INTP COMPU-SCALE has exactly one LOWER-LIMIT and no UPPER-LIMIT |
B.53 | A COMPUCODE direction contains only PROG-CODE |
B.54 | Unit conversion members are specified together |
B.56 | Sibling elements of one wrapper carry distinct SHORT-NAMEs |
B.57 | Each SCALE-CONSTR range fits inside the INTERNAL-CONSTR range |
B.59 | An IDENTICAL conversion keeps the base data type, except ASCII/UTF-8 may widen to Unicode |
B.60 | A computing conversion has numeric types on both sides |
B.61 | A TEXTTABLE converts to A_UNICODE2STRING |
B.64 | Each declared conversion direction has the required COMPU-SCALE count |
B.69 | The IDENT-VALUEs of one EXPECTED-IDENT share one TYPE |
B.71 | A PHYS-SEGMENT’s START-ADDRESS does not exceed its END-ADDRESS |
B.72 | A CHECKSUM stating both source addresses states them in order |
B.73 | A FILTER’s FILTER-START does not exceed its FILTER-END |
B.74 | A SEGMENT stating both source addresses states them in order |
B.75 | Flash ident values are readable as the schema datatype their TYPE names — A_UINT32 as xsd:unsignedInt, A_BYTEFIELD as xsd:hexBinary |
B.80 | A CHECKSUM’s UNCOMPRESSED-SIZE, when present, is greater than zero |
B.83 | PHYS-SEGMENT address ranges of one PHYS-MEM do not overlap |
B.96 | No PROTOCOL-SNREF at a DIAG-COMM inside a PROTOCOL layer |
B.99 | TABLE-ROW/KEY is unique inside a TABLE, referenced rows included |
B.104 | A layer holds at most one STARTCOMM and one STOPCOMM service, inherited and imported ones included |
B.105 | A layer holds at most one DEFAULT-FAULT-READ service (warning) |
B.107 | A session does not reference one data block twice |
B.114 | Numeric coded types use a length-stating encoding |
B.116 | A LENGTH-KEY’s DOP converts to A_UINT32 |
B.122 | LOWER-LIMIT does not exceed UPPER-LIMIT, and an equal pair is closed on both ends |
B.130 | Every COMPU-SCALE states a LOWER-LIMIT, except LINEAR and RAT-FUNC |
B.139 | A LOGICAL-LINK names one of the four permitted layer combinations |
B.145 | A float coded type is a correctly sized STANDARD-LENGTH-TYPE |
B.151 | COMPU-SCALEs of one wrapper do not overlap, except under TEXTTABLE |
B.156 | A structure’s stated BYTE-SIZE covers where its parameters end (warning) |
B.157 | DOCREF and DOCTYPE travel together or not at all |
B.158 | An ODX category agrees with its lowercase file extension |
B.161 | A PHYSICAL-DEFAULT-VALUE exists only where the referenced DOP can convert it |
B.165 | Rational coefficient counts fit their conversion category |
B.172 | A scale with no upper limit has a closed lower limit |
B.185 | TROUBLE-CODE and SHORT-NAME map one-to-one across local, referenced, and linked DTCs after exclusions |
B.186 | A COMPARAM-REF carries the value shape required by its target |
B.213 | CONDENSED=true carries a BIT-MASK |
B.223 | A DATABLOCK’s referenced flash format has USER-SELECTION exactly for USER-DEFINED |
B.227 | No OID is handed out twice in the PDX data pool |
C.PARAM-ID | Only a TABLE-KEY parameter carries an xsd:ID (warning) |
C.NRC-CONST | NRC-CONST states its codes inside the mandatory CODED-VALUES wrapper |
C.CPUSAGE | A BASE-COMPARAM declares the required CPUSAGE |
C.DDDS-ORDER | DIAG-DATA-DICTIONARY-SPEC children keep the schema’s sequence order |
C.ENV-DATA-DESC | An ENV-DATA-DESC carries the parameter that selects the trouble code |
C.VEHICLE-INFO-ID | VEHICLE-INFORMATION declares OID, not ID (warning) |
C.PVL-PIN-REFS | A PHYSICAL-VEHICLE-LINK names the pins it is wired to |
C.SDG-CAPTION-ID | An SDG-CAPTION carries the identifier the schema makes mandatory |
NRC-CONST-SET | A negative response position carries its codes in one NRC-CONST, not a stack of them |
ID-UNIQUE | No ID is handed out twice within one XML document |
BIT-LENGTH-REQUIRED | A fixed-length coded type states its BIT-LENGTH |
DOCUMENT-READABLE | Every document of the archive parses |
PDX-CATALOG | Enforced catalogue subset: fixed version, required names, non-empty present wrappers, valid update states, and incremental omission rules |
The profile does not run the complete Annex C XML Schema and does not implement the complete Annex B checker table. Concretely: 56 of at least 181 real Annex B rules, roughly 31% — and because 30 further table rows resist extraction, 181 is a lower bound on the denominator and 31% an upper bound on the coverage. An empty finding list is not an ISO conformance certificate.
The overlapping rules are cross-checked against an independent Python
implementation (udsdoc); a disagreement
fails CI in both repositories. B.31 and B.51 are deliberately excluded because
the two implementations have different resolution and sizing reach, and
PDX-CATALOG is archive-scoped on this side. The exact overlap is derived from
both sources in CI rather than copied here. This is a strong guarantee over a
narrow slice: it says nothing about the 125 rules neither implementation
enforces, and where both share a misreading it says nothing at all. That has
happened once here, in NRC-CONST. See
CONFORMANCE.md
for the audit
basis, exact boundary, and required complementary checks. A packaged member
absent from the catalogue is not reported by this profile. An incremental
ABLOCK may intentionally list a file omitted from the archive when UPD is
UNCHANGED, UNUSED, REUSED, or DELETED.
§The odx command
The crate ships an installable command, so a container can be checked without writing any Rust:
cargo install odx-rs
odx validate container.pdx # every finding, then a count
odx validate container.pdx --format json # the findings array, nothing else
odx validate container.pdx --format sarif # for GitHub code scanning
odx validate container.pdx --strict # warnings fail the run too
odx validate loose-odx-dir/ # a directory of loose .odx-*
# documents, e.g. what an
# authoring tool leaves behind
odx tree container.pdx --depth 3 # the parsed structure
odx tree container.pdx --format json # the same, as data
odx summary container.pdx --format json # counts per node kind
odx dops container.pdx # the machine-readable DOP index
odx rules --format json # validation profile IDsExit codes are the part a CI job depends on:
| Code | Meaning |
|---|---|
| 0 | the container was read, and nothing was reported at the failing level |
| 1 | findings were reported at the failing level |
| 2 | the container could not be read at all, or the arguments were wrong |
The gap between 1 and 2 is deliberate: a pipeline that produced no file must not be mistaken for one that produced a good file.
The binary lives behind the cli feature, which is on by default. A dependent
that only wants the library takes it out:
[dependencies]
odx-rs = { version = "0.38", default-features = false }cargo run --example validate -- container.pdx remains as a minimal, readable
example of calling validate yourself.
§Options
parse_with_options puts the limits that keep the model small under the
caller’s control. SDGS is where tools park data of their own, and a container
may carry more of it than a property table can usefully show:
use odx_rs::ParseOptions;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let bytes = std::fs::read("container.pdx")?;
let options = ParseOptions { max_sdg_rows: None };
let document = odx_rs::parse_with_options(&bytes, "container.pdx", options)?;
println!("{} roots", document.roots.len());
Ok(())
}The default retains every SDG row. Set max_sdg_rows to Some(limit) only when
a presentation layer needs an explicit bound; whenever rows are then dropped,
the element gains an SDG-TRUNCATED property holding the number left out.
§What is read
- Catalogue (
index.xml) and vehicle information (.odx-v). - Diagnostic layers (
.odx-d) — protocols, functional groups, shared data, base variants and ECU variants, with their services, single ECU jobs, requests and responses, data object properties, structures, tables, environment data, state charts, function classes and communication parameters.- Inheritance follows
PARENT-REFin the order ODX ranks layers, honoursNOT-INHERITED-DIAG-COMM/NOT-INHERITED-DOP, and reports both where an element was inherited from and what a local definition overrides. - Complex parameters — a parameter pointing at a structure, a repeating
field (
END-OF-PDU-FIELD,STATIC-FIELD,DYNAMIC-LENGTH-FIELD) or a multiplexer is expanded into nested rows with byte positions rebased onto the parent.
- Inheritance follows
- Multiple ECU jobs (
.odx-m), the function dictionary (.odx-fd), comparam specs (.odx-c), comparam subsets (.odx-cs) and flash containers (.odx-f). SDGSspecial data wherever it appears, with nested groups keeping their path.
§Reading the model as data
The tree renders for a person: badges and property rows are display strings whose format is a presentation choice, not an interface. Beside it are flat indexes meant for a program, so nothing has to be parsed back out of prose.
The tree itself serialises too — odx tree --format json, or serde_json on
an OdxDocument. Every node keeps its shortName, and every parameter its
bytePosition, bitPosition, bitLength, kind, codedValue and
codedValues, and dopKind names what its DOP-REF points at so a join
against dops can tell “a kind that index does not hold” from “nothing at
all”. That is what a generator needs to assert its own output came
back unchanged: udsdoc’s browser edition compares each message’s byte template,
its exact per-parameter layout and its set of negative-response codes against
what this reader made of the archive it just wrote.
document.dops lists every DATA-OBJECT-PROP once. Besides its conversion —
the scales of a COMPU-METHOD with their rational coefficients, limits and
COMPU-CONST text, plus inverse_scales for the COMPU-PHYS-TO-INTERNAL
direction an encoder needs — each entry carries what it takes to actually
decode a value:
| Field | Why it is not enough to have the bit length |
|---|---|
base_data_type | how the bytes on the wire are read |
physical_base_data_type | what the value becomes; differs whenever the conversion does anything |
coded_type_kind | the DIAG-CODED-TYPE xsi:type — a MIN-MAX-LENGTH-TYPE has no bit length at all |
high_low_byte_order | reported as its effective value: ODX defaults it to true, and guessing gives a plausible wrong number rather than an error |
document.services is the same idea for services, with one difference that
matters: it records the layer each entry belongs to and, when the layer
inherited rather than declared it, the layer that defined it. “What does this
ECU variant answer to” and “how many services exist” are different questions —
the first counts entries, the second counts entries with no inherited_from —
and a list that forgot the layer answers neither. Each entry carries the
numeric service identifier, the request and response IDs, the functional
classes it is filed under, and the states a PRE-CONDITION-STATE-REF requires,
resolved to names.
document.dtcs is the same idea for trouble codes: the numeric
TROUBLE-CODE, the display form a technician reads, the text, the level and
the DTC-DOP that declared it.
document.summary carries the counts parser_info renders as prose — layers,
services, DOPs, DTCs, jobs, environment data, flash blocks, and how many
archive entries failed to parse. Both are built from one set of values so they
cannot drift. It counts what the tree shows, each definition once and
diagnostic layers only, which is deliberately narrower than dops; the doc
comments say so on both sides.
A parameter row names the DOP it uses in dop_ref and keeps its
bit_position, so two four-bit values sharing a byte stay distinguishable. It
also carries kind (the xsi:type, which semantic silently falls back to)
and coded_value (the number, where it has exactly one) — so telling a
CODED-CONST from a VALUE, or comparing against an expected byte, does not
mean reading "0x22" back out of a string whose width depends on the bit
length.
The model is serde-serialisable, so it can be handed to another language or
written out as JSON directly — which is what odx dops and
odx summary --format json do.
§ODX without a PDX
A .odx-d on its own is what comes out of version control, out of an authoring
tool, and out of a generator writing loose files. parse_documents and
validate_documents read those directly, and the odx command takes a
directory:
let layer = std::fs::read("Sample.odx-d")?;
let subset = std::fs::read("ISO_15765_2.odx-cs")?;
let findings = odx_rs::validate_documents(vec![
("Sample.odx-d".into(), layer),
("ISO_15765_2.odx-cs".into(), subset),
]);Both take a set rather than one document on purpose. ODX cross-document references are ordinary — a diagnostic layer points at the comparam subset beside it — and a reference whose target was simply not supplied looks exactly like one that is broken. Hand over the documents that travel together and they resolve; hand over one and the rest are reported unresolved, which is true but rarely what you meant.
The PDX catalogue rules do not run here: a loose document never claimed to be a
package, so a missing index.xml would be a fact about the call rather than
about the data. Everything else is checked exactly as it would be inside a
container.
§Limits
The reader takes untrusted input: the browser viewer hands it whatever file is
dropped on the page, in a module built with panic = "abort", where a failed
allocation ends the page rather than returning an error. Inflation is therefore
bounded — 64 MiB per document, 256 MiB across an archive, at most 65,536
entries, never more than 4 MiB reserved on the size an archive claims in its
own header, and at most 256 levels of element nesting (real ODX nests 14 deep;
the passes over a parsed tree recurse once per level, so a deeper document
overflowed the stack). A document over a limit is reported as skipped, so it appears
under Problems rather than disappearing from a container that would otherwise
look complete.
§Scope
odx-rs reads descriptions; it does not talk to a vehicle and does not decode
live ECU responses. See
CONFORMANCE.md
for the exact validation boundary and
ROADMAP.md
for every adopted, deferred,
and rejected extension considered in the 2026-08-02 audit.
§License
MIT
§Design notes
Reader for ODX diagnostic descriptions.
The subject of this crate is ODX itself: the XML documents that describe
how to talk to an ECU. A PDX file is just how they travel, so parse
opens that ZIP archive (container), reads every document in it (xml)
and maps the result onto a navigable model (odx).
The crate is plain Rust: it has no browser dependency, so it can be used
from a command line tool or a test as easily as from WebAssembly. The
bindings live in the pdx-wasm crate next to this one.
Re-exports§
pub use model::MessageDirection;pub use model::OdxCompuScale;pub use model::OdxDocument;pub use model::OdxDop;pub use model::OdxMessage;pub use model::OdxNode;pub use model::OdxNodeKind;pub use model::OdxParam;pub use model::OdxProperty;
Modules§
- model
- Serialisable ODX model.
Structs§
- Finding
- One thing that is wrong with a container.
Marked
#[non_exhaustive]: this type gains fields as the reader learns to read more of ODX, and every such addition would otherwise be a source- breaking change for anyone constructing it. Build one with..Default::default()or read it field by field. - Parse
Error - Parse
Options - Knobs that change how much of a container ends up in the model.
Enums§
- Error
Kind - What went wrong, so a caller can react differently per cause.
- Severity
- How much a finding matters.
Functions§
- inspect
- The model and the findings, from one read of the container.
- inspect_
with_ options inspect, with the limits ofParseOptionsunder the caller’s control.- name
- Name of this crate, shown next to the version in the viewer.
- parse
- Reads a PDX container and returns the model the viewer renders.
- parse_
documents - Reads loose ODX documents — a
.odx-dand the.odx-csbeside it, say — without a PDX archive around them. - parse_
documents_ with_ options parse_documents, with the limits ofParseOptionsunder the caller’s control.- parse_
with_ options parse, with the limits ofParseOptionsunder the caller’s control.- validate
- Checks a PDX archive against this crate’s Annex B / Annex C profile.
- validate_
documents - Checks loose ODX documents against the same profile
validateapplies to an archive, minus the rules that judge the package itself. - validation_
rule_ ids - Rule identifiers the current validation profile can report.
- version
- Version of this crate, shown in the viewer’s status bar and About dialog.