Skip to content

Proposal: compile DBC files into a plain-C const database for PGN, CAN ID, and SPN lookup #3

Closed

Description

@ip332

Goal

Replace the generated std::map<uint32_t, PGN> with a DBC compiled into plain C: const tables in .rodata, no constructors, no heap, and a small C runtime that finds a message by PGN or CAN ID and a signal by SPN number or name.

The host compiler can stay C++. Only the emitted database and the lookup/codec used on the ECU need to be ISO C.

This is the streaming database (every message in the DBC). The message-centric path (one struct per message the ECU actually touches) can keep generating accessors, but those accessors should be shift-and-mask macros, not C bitfields. See the union issue for why the current union output cannot be this database.

What is wrong with the C++ table

DbcParser::generatePgnOutput emits:

std::map<uint32_t, PGN> j1939_dbc = { ... };

PGN / SPN (j1939_parser/j1939_frame.h) hold std::string, std::vector, and std::map<uint32_t, std::string>. Initializing that map allocates tree nodes and strings before main. J1939Parser::getPgn then does two std::map::find calls, and PGN::signalByName walks every signal with strcmp. That contradicts the README claim of allocation-free, safety-critical ECU code.

SPN numbers are not in the table at all. The parser never reads BA_ "SPN".

Generated layout

Shared declarations live in a C header (j1939_db.h), not in the generated file. The compiler emits one .h (the extern symbol) and one .c (the bytes).

typedef enum {
    J1939_SIG_SIGNED       = 1u << 0,
    J1939_SIG_LITTLE_ENDIAN= 1u << 1,
    J1939_SIG_MULTIPLEXOR  = 1u << 2,
    J1939_SIG_MULTIPLEXED  = 1u << 3,
    J1939_SIG_BYTES        = 1u << 4  /* length is in bits but value is a byte string, not a uint64 */
} j1939_sig_flags_t;

typedef struct {
    uint32_t value;
    uint32_t name_off;          /* offset into the string blob; ~0u if strings were stripped */
} j1939_enum_t;

typedef struct {
    uint32_t name_off;
    uint32_t spn;               /* 0 when the DBC has no SPN attribute */
    uint16_t start_bit;         /* DBC bit numbering, Intel or Motorola as flagged */
    uint16_t length;            /* bits; may exceed 64 when J1939_SIG_BYTES is set */
    uint16_t enum_begin;        /* index into enums[]; count 0 = no VAL_ */
    uint16_t enum_count;
    uint16_t mux_value;         /* meaningful when J1939_SIG_MULTIPLEXED */
    uint16_t flags;
    double scale;               /* see "scale and offset" below */
    double offset;
    double min_value;
    double max_value;
} j1939_signal_t;

typedef struct {
    uint32_t name_off;
    uint32_t pgn;               /* 0 for an 11-bit frame */
    uint32_t can_id;            /* 11-bit id, or 29-bit id with SA and priority already masked off */
    uint32_t sa_mask;           /* 0xFF when this row is specific to one source address, else 0 */
    uint8_t  sa;                /* significant only when sa_mask != 0 */
    uint8_t  extended;          /* 0 = standard CAN id, 1 = J1939 extended */
    uint16_t dlc;               /* nominal payload bytes, up to 1785 */
    uint16_t signal_begin;      /* contiguous slice of signals[] */
    uint16_t signal_count;
} j1939_message_t;

typedef struct {
    uint32_t spn;
    uint16_t message_index;
    uint16_t signal_index;      /* index into that message's slice, not into the global array */
} j1939_spn_ref_t;

typedef struct {
    const char *strings;
    const j1939_message_t *messages;     /* sorted by (extended, key) */
    uint16_t message_count;
    const j1939_signal_t *signals;
    const j1939_enum_t *enums;
    const j1939_spn_ref_t *spn_index;    /* sorted by spn, only rows with spn != 0 */
    uint16_t spn_count;
} j1939_db_t;

Keys:

  • Standard frame: can_id & 0x7FF. Priority bits are not part of an 11-bit id.
  • Extended frame: the J1939 PGN. PDU1 (PF < 240) is DP << 16 | PF << 8 (destination is not part of the PGN). PDU2 is DP << 16 | PF << 8 | PS. Priority and source address are not part of the key. The EFF flag (0x80000000) is not part of the key; extended is a separate column.
  • Several DBC rows that share a PGN but are not identical stay as a contiguous run of equal keys. sa_mask == 0xFF means "this layout is for this source address only". sa_mask == 0 means "this layout is the generic one". Lookup prefers an SA-specific row, then the generic row. Rows that differ only by priority collapse to one row.

messages[] is sorted so lookup is bsearch (or an explicit binary search, which is easier to bound). A full J1939 or NMEA 2000 database is on the order of 10^3 messages, so this is about eleven comparisons, all in flash. A perfect hash is an optimization for later, not the first cut: a sorted table is reviewable and has a hard upper bound.

Signal name lookup inside one message stays a linear scan. Messages have few signals. Cross-message lookup by SPN is the sorted spn_index. Cross-message lookup by name (pgnFor) is a second sorted index of {name_off, message_index} built from the same string blob, or a scan of messages[] if the database was built with -no-strings and the caller only has SPN numbers.

String blob: one const char strings[]. Every name is an offset, so identical names are stored once and a "no strings" build (-no-strings) leaves name_off == ~0u and omits the blob. The ECU then uses SPN numbers and generated #define EEC1_PGN 0xF004 / #define ENG_SPEED_SPN 190.

Scale and offset

DBC factors are decimal literals. Store them as double in the const table (the current float truncates). On targets that cannot use floating point, add a later -fixed mode that parses the decimal text into int64_t scale_num / uint32_t scale_den without a binary float round-trip. Do not store float.

Runtime API

Implemented once, in C, shared by every database:

void j1939_id_unpack(uint32_t can_id, int extended,
                     uint32_t *pgn, uint8_t *sa, uint8_t *da, uint8_t *priority);

const j1939_message_t *j1939_db_find(const j1939_db_t *db,
                                     uint32_t can_id, int extended);

const j1939_signal_t *j1939_signal_by_spn(const j1939_db_t *db, uint32_t spn,
                                          const j1939_message_t **message);

const j1939_signal_t *j1939_signal_by_name(const j1939_db_t *db,
                                           const j1939_message_t *message,
                                           const char *name);

/* Returns 0 on success. Signals wider than 64 bits without J1939_SIG_BYTES fail. */
int j1939_signal_raw(const uint8_t *payload, uint16_t dlc,
                     const j1939_signal_t *sig, uint64_t *raw);
double j1939_signal_phys(const j1939_signal_t *sig, uint64_t raw);
int j1939_signal_store(uint8_t *payload, const j1939_signal_t *sig, double phys);

/* Byte-string signals (names, VIN, ASCII). Copies min(dst_size-1, length/8) and NUL-terminates. */
int j1939_signal_bytes(const uint8_t *payload, uint16_t dlc,
                       const j1939_signal_t *sig, char *dst, uint16_t dst_size);

j1939_db_find is the only message lookup. It does not try the raw CAN id (priority, SA, destination, EFF) and then the PGN. That is the current J1939Parser::getPgn behavior and it misses frames.

Multiplexed signals: the row with J1939_SIG_MULTIPLEXOR is read first; a multiplexed row is visible only when its mux_value matches. The parser has to actually record the m0 / m1 suffix it currently skips in Signal::Signal.

J1939Parser becomes a thin C++ wrapper over this API so the existing tests keep a C++ entry point. New tests call the C API directly.

Compiler work

dbc_compiler gains -c_path db.c. It still accepts -pgn_path until callers move over.

  1. Parse BA_DEF_ / BA_ "SPN" SG_ (and the message-level BA_ "SPN" BO_ if present). Parse multiplex indicators on SG_ instead of skipping them. Parse CM_ only if we want comments in the string blob; not required for lookup.
  2. Apply an explicit collapse rule, covered by tests:
    • identical layout (including endianness) under one PGN → one generic row;
    • same PGN, different layout, different source address → one SA-specific row each, plus a generic row only when one of them is marked as the default (DLC is not a proxy for "default");
    • priority is never part of identity.
  3. Emit sorted messages[] and spn_index[]. Fail the compiler if two generic rows share a key and are not identical.
  4. Round-trip test: compile tests/dbc/j1939.dbc and tests/dbc/big_endian_database.dbc with gcc -std=c11 -Wall -Werror, then decode the same frames through the C database and through the current C++ map and compare raw values.

Out of scope for the first cut

  • Perfect hashing.
  • Fixed-point scale (-fixed).
  • Generating per-message shift/mask accessors (follow-up to the union output).
  • Changing transport-protocol reassembly. The database is consulted after a frame, or a reassembled payload, exists.

Activity

  1. ip332 commented on Nov 19, 2026

    @ip332
    OwnerAuthor

    Related findings from the same review:

    #4, #5, #6, and #8 are constraints on this database. #7 should stay a separate, optional, message-centric output, and should emit shift-and-mask accessors rather than become the lookup table.

  2. ip332 commented on Nov 19, 2026

    @ip332
    OwnerAuthor

    Implemented on branch plain-c-dbc-database.

    dbc_compiler -c_path emits a const C11 database for PGN, CAN ID, and SPN lookup. The runtime is j1939_db.c. Identical layouts collapse to one generic row, and BA_ "J1939Default" marks the generic row when layouts differ.

    See the pull request for the change and the test plan.

  3. ip332 commented on Nov 19, 2026

    @ip332
    OwnerAuthor

    Pull request: #9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions