8000 feat: preserve CDD service preconditions by tomrford · Pull Request #52 · tomrford/gocan · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ ISO-TP and UDS, with semantic codecs for DBC and CANdela diagnostic data.
| `dbc` | DBC parsing and semantic CAN frame encoding and decoding |
| `isotp` | ISO-TP payload transport over classical CAN and CAN FD |
| `uds` | Raw exchanges and typed Unified Diagnostic Services operations |
| `cdd` | CANdela data-identifier parsing and semantic UDS record encoding and decoding |
| `cdd` | CANdela data-identifier parsing, session and security preconditions, and semantic UDS record encoding and decoding |

## Driver support

Expand Down
84 changes: 74 additions & 10 deletions cdd/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,28 @@ import "github.com/tomrford/gocan/internal/scalar"

// Database is the resolved catalog from the first ECU and its first variant in
// a CDD document. DIDs remain in source order.
//
// States retains every declared state in document order. Sessions and
// SecurityLevels contain the states of the corresponding CDD groups, including
// any locked state. These are literal document metadata, not UDS subfunctions
// or a hierarchy of access privileges.
type Database struct {
DIDs []DID
Diagnostics []Diagnostic
DIDs []DID
States []State
Sessions []State
SecurityLevels []State
Diagnostics []Diagnostic

didsByName map[string]int
didsByIdentifier map[uint16]int
}

// Diagnostic reports a data identifier dropped from the catalog without making
// the database unsafe to use: layouts outside the supported subset, unresolved
// references, and duplicate names or identifiers. Name is the QUAL of the
// dropped diagnostic instance, which CDD documents may leave empty.
// Diagnostic reports a defect confined to one data identifier that leaves the
// database safe to use. A DID is dropped from the catalog when its layout is
// outside the supported subset, its references do not resolve, or its name or
// identifier repeats. Unresolved execution preconditions leave the DID usable
// for encoding and decoding, with an error on the affected Precondition. Name is
// the QUAL of the diagnostic instance, which CDD documents may leave empty.
type Diagnostic struct {
Name string
Message string
Expand All @@ -44,17 +54,71 @@ type DID struct {
// when the last field is variable length, in which case MaxLength is the
// largest record.
//
// Preconditions preserves alternative service conditions in source order.
// There is one entry per source service bound to this supported record
// operation, even when conditions are equivalent.
// Conditions from different alternatives must not be combined. An unresolved
// alternative has Err set; it does not prevent encoding or decoding the record.
//
// Treat a Record and its Fields as read-only: Encode and Decode trust the
// layout that Parse resolved, and modifications are not revalidated.
type Record struct {
Name string
Length uint32
MaxLength uint32
Fields []Field
Name string
Length uint32
MaxLength uint32
Fields []Field
Preconditions []Precondition

codec *recordCodec
}

// SourceIdentity retains the XML id, oid, temploid and QUAL of a CDD object.
// Missing attributes remain empty; qualifiers need not be unique. These values
// identify document objects and must not be used as UDS subfunctions.
type SourceIdentity struct {
ID string
OID string
TemplateOID string
Qualifier string
}

// State is a literal CDD state and its containing group. Index is its one-based
// position across all STATEGROUPS/STATE entries, including unsupported groups.
// GroupIndex is the one-based position of its STATEGROUP. Index describes
// source order only; its relationship to mayBeExec values is not established.
// Neither index is a UDS subfunction. No initial state is inferred.
type State struct {
Source SourceIdentity
Index int
Group SourceIdentity
GroupIndex int
GroupSpec string
}

// Precondition describes one source service's execution requirements.
// ServiceIndex is its one-based position among all SERVICE children of the
// diagnostic instance, including services outside the supported DID subset.
// TemplateRef is the instance's literal tmplref.
//
// Check Err first: a non-nil error means unknown requirements, not ECU rejection.
// A nil Err means no explicit CDD restriction was found on the service or its
// template. This does not establish ECU permission. Callers manage ECU state.
//
// Raw rule pointers distinguish missing attributes from explicit empty values.
// Parse currently leaves every explicit rule unresolved because the CDD index,
// omitted-group, exclusion and inheritance rules have not been verified.
// Resolved restrictions are not exposed until those rules are established.
type Precondition struct {
Service SourceIdentity
ServiceIndex int
TemplateRef string
MayBeExec *string
NotExecInStateGroups *string
TemplateMayBeExec *string
TemplateNotExecInStateGroups *string
Err error
}

// Values maps DID field names to their physical values. Encoding accepts Go
// numeric values, strings for ASCII fields, and choice labels.
type Values map[string]any
Expand Down
98 changes: 89 additions & 9 deletions cdd/parse.go
7364
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,13 @@ type resolver struct {
datatypes map[string]*element
}

func sourceIdentity(node *element) SourceIdentity {
return SourceIdentity{
ID: node.attr("id"), OID: node.attr("oid"),
TemplateOID: node.attr("temploid"), Qualifier: node.childText("QUAL"),
}
}

func newResolver(name string, ecuDoc *element) *resolver {
resolver := &resolver{
name: name,
Expand Down Expand Up @@ -105,40 +112,68 @@ func (resolver *resolver) resolve() (*Database, error) {
didsByName: make(map[string]int),
didsByIdentifier: make(map[uint16]int),
}
for groupIndex, group := range resolver.ecuDoc.child("STATEGROUPS").childrenNamed("STATEGROUP") {
identity := sourceIdentity(group)
for _, node := range group.childrenNamed("STATE") {
state := State{
Source: sourceIdentity(node), Index: len(database.States) + 1,
Group: identity, GroupIndex: groupIndex + 1, GroupSpec: group.attr("spec"),
}
database.States = append(database.States, state)
switch state.GroupSpec {
case "session":
database.Sessions = append(database.Sessions, state)
case "security":
database.SecurityLevels = append(database.SecurityLevels, state)
}
}
}
for _, class := range variant.childrenNamed("DIAGCLASS") {
for _, instance := range class.childrenNamed("DIAGINST") {
did, selected, err := resolver.resolveDID(instance)
if !selected {
continue
}
if err != nil {
database.drop(instance.childText("QUAL"), err)
database.report(instance.childText("QUAL"), err)
continue
}
if previous, exists := database.didsByName[did.Name]; exists {
database.drop(did.Name, sourceError(resolver.name, "name repeats DID %#04x", database.DIDs[previous].Identifier))
database.report(did.Name, sourceError(resolver.name, "name repeats DID %#04x", database.DIDs[previous].Identifier))
continue
}
if previous, exists := database.didsByIdentifier[did.Identifier]; exists {
database.drop(did.Name, sourceError(resolver.name, "identifier %#04x is already used by DID %q", did.Identifier, database.DIDs[previous].Name))
database.report(did.Name, sourceError(resolver.name, "identifier %#04x is already used by DID %q", did.Identifier, database.DIDs[previous].Name))
continue
}
database.didsByName[did.Name] = len(database.DIDs)
database.didsByIdentifier[did.Identifier] = len(database.DIDs)
database.DIDs = append(database.DIDs, did)
for _, record := range []*Record{did.Read, did.Write} {
if record == nil {
continue
}
for _, condition := range record.Preconditions {
if condition.Err != nil {
database.report(did.Name, condition.Err)
}
}
}
}
}
return database, nil
}

func (database *Database) drop(name string, err error) {
func (database *Database) report(name string, err error) {
database.Diagnostics = append(database.Diagnostics, Diagnostic{Name: name, Message: err.Error()})
}

// resolveDID resolves one diagnostic instance. The boolean reports whether the
// instance is a data identifier at all; an unselected instance is some other
// diagnostic class and is not a defect. A selected instance that cannot be
// resolved returns an error for the caller to record as a diagnostic.
// resolved returns an error for the caller to record as a diagnostic. A
// precondition that cannot be resolved is retained as an unresolved alternative
// on the operation; the caller reports it after accepting the DID.
func (resolver *resolver) resolveDID(instance *element) (DID, bool, error) {
classTemplate := resolver.byID[instance.attr("tmplref")]
if classTemplate == nil || classTemplate.name != "DCLTMPL" {
Expand Down Expand Up @@ -179,27 +214,40 @@ func (resolver *resolver) resolveDID(instance *element) (DID, bool, error) {
if err != nil {
return DID{}, true, fmt.Errorf("DID %q read record: %w", name, err)
}
resolver.resolvePreconditions(did.Read, bindings.readServices, "read")
}
if bindings.writeData != nil {
did.Write, err = resolver.resolveDIDRecord(name, instance, classTemplate, bindings.writeData)
if err != nil {
return DID{}, true, fmt.Errorf("DID %q write record: %w", name, err)
}
resolver.resolvePreconditions(did.Write, bindings.writeServices, "write")
}
return did, true, nil
}

// didBindings holds each operation's components and service alternatives.
type didBindings struct {
identifiers map[string]struct{}
readData map[string]struct{}
writeData map[string]struct{}
identifiers map[string]struct{}
readData map[string]struct{}
writeData map[string]struct{}
readServices []boundService
writeServices []boundService
}

// boundService pairs a SERVICE instance with the DCLSRVTMPL it was resolved
// against, so precondition resolution never repeats the lookup.
type boundService struct {
instance *element
template *element
index int
}

// didServiceComponents retains the message direction because a read response
// and write request may bind different proxies even when their layouts agree.
func (resolver *resolver) didServiceComponents(instance, classTemplate *element) didBindings {
bindings := didBindings{identifiers: make(map[string]struct{})}
for _, service := range instance.childrenNamed("SERVICE") {
for index, service := range instance.childrenNamed("SERVICE") {
serviceTemplate := resolver.byID[service.attr("tmplref")]
if serviceTemplate == nil || serviceTemplate.name != "DCLSRVTMPL" || !directChild(classTemplate, serviceTemplate) {
continue
Expand All @@ -216,13 +264,45 @@ func (resolver *resolver) didServiceComponents(instance, classTemplate *element)
switch sid {
case 0x22:
bindings.readData = collectDataComponents(protocolService.child("POS"), bindings.readData)
bindings.readServices = append(bindings.readServices, boundService{service, serviceTemplate, index + 1})
case 0x2e:
bindings.writeData = collectDataComponents(protocolService.child("REQ"), bindings.writeData)
bindings.writeServices = append(bindings.writeServices, boundService{service, serviceTemplate, index + 1})
}
}
return bindings
}

// resolvePreconditions retains rule presence and text without inferring the
// meaning of state indexes, omitted groups, exclusions or template inheritance.
func (resolver *resolver) resolvePreconditions(record *Record, services []boundService, operation string) {
for _, service := range services {
condition := Precondition{
Service: sourceIdentity(service.instance),
ServiceIndex: service.index,
TemplateRef: service.instance.attr("tmplref"),
MayBeExec: attributeValue(service.instance, "mayBeExec"),
NotExecInStateGroups: attributeValue(service.instance, "notExecInStateGroups"),
TemplateMayBeExec: attributeValue(service.template, "mayBeExec"),
TemplateNotExecInStateGroups: attributeValue(service.template, "notExecInStateGroups"),
}
if condition.MayBeExec != nil || condition.NotExecInStateGroups != nil ||
condition.TemplateMayBeExec != nil || condition.TemplateNotExecInStateGroups != nil {
err := sourceError(resolver.name, "CDD execution rule semantics are not verified (state indexes, omitted groups, exclusions and inheritance)")
condition.Err = fmt.Errorf("DID %q %s service %d (id %q, oid %q, template %q): %w", record.Name, operation, service.index, condition.Service.ID, condition.Service.OID, condition.TemplateRef, err)
}
record.Preconditions = append(record.Preconditions, condition)
}
}

func attributeValue(node *element, name string) *string {
value, present := node.attrs[name]
if !present {
return nil
}
return &value
}

func directChild(parent, candidate *element) bool {
for _, child := range parent.children {
if child == candidate {
Expand Down
Loading
0