From 6d46517d252c24deb3d2f7b88c2ad65a03a26038 Mon Sep 17 00:00:00 2001 From: Igor Prilepov Date: Sun, 22 Nov 2026 17:45:40 -0800 Subject: [PATCH] Generate portable payload accessors and document embedded output --- README.md | 85 ++++++++++++++---- dbc_compiler/dbc_compiler.cpp | 15 +++- j1939_parser/dbc_parser/dbc_accessors.cpp | 96 +++++++++++++++++++++ j1939_parser/dbc_parser/dbc_c_gen_tests.cpp | 82 ++++++++++++++++++ j1939_parser/dbc_parser/dbc_parser.h | 3 + 5 files changed, 261 insertions(+), 20 deletions(-) create mode 100644 j1939_parser/dbc_parser/dbc_accessors.cpp diff --git a/README.md b/README.md index ec8d0a1..08959c9 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [![Build](https://github.com/ip332/j1939/actions/workflows/build.yml/badge.svg)](https://github.com/ip332/j1939/actions/workflows/build.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) -A C++14 library for encoding and decoding J1939/CAN frames, plus a DBC compiler that turns `.dbc` files into compact, statically-typed C/C++ code — no runtime parsing, no dynamic allocation, suitable for safety-critical ECU code. +A C++14 library for encoding and decoding J1939/CAN frames, plus a DBC compiler. For embedded targets, `-c_path` produces a plain-C const database with no constructors, allocation, or runtime DBC parsing. The C++ PGN map and host tools use dynamic allocation. This project does not establish safety certification. ## Summary @@ -19,12 +19,12 @@ Both scenarios could be addressed with the same implementation, but the message- Regardless of the use case, encoding and decoding should behave consistently across all modules and subsystems. One option is to parse a DBC file at runtime, as the roscan project does, but this approach may not be acceptable for safety-critical applications. Compiling the DBC at build time also allows more thorough validation. -This project therefore provides a DBC compiler that generates output in two formats — **PGN** and **Union** — from one or more input files. +This project therefore provides a DBC compiler that generates a **plain-C database**, **portable accessors**, a **C++ PGN map**, and a legacy **packed union** — from one or more input files. ## Content * **J1939** — the library combining the DBC parser, runtime data types, and the J1939 encoding/decoding functionality. Built as a static library. -* **dbc_compiler** — the DBC compiler itself, which processes multiple input files and generates output code in the two formats described below. +* **dbc_compiler** — the DBC compiler itself, which processes multiple input files and generates the output formats described below. * **tests** — the unit test suite covering most of the library's components. * **can_reader** — a collection of classes, built as a static library, that handle long (multi-frame) messages and reading/writing a physical CAN port via the SocketCAN API. * **options** — a lightweight command-line parser. May be replaced with **gflags** in the future (TBD). @@ -121,18 +121,63 @@ Average bus load: 8000.47 bytes/sec; duration: 23.615 sec. 1000.08 msg/sec ``` -##### PGN format -The first format produces a single file where **all input DBC files** are compiled into one `std::map`: +##### Plain-C database (embedded lookup) + +```bash +bin/dbc_compiler -in tests/dbc/j1939.dbc -c_path generated_db.c +``` + +This writes `generated_db.c` and `generated_db.h`. Compile the generated C file +and `j1939_parser/j1939_db.c` with the target's C11 compiler and include the generated +header. All database storage is const arrays and a string blob, with a +`const j1939_db_t` entry point declared in the generated header. Loading the tables +runs no constructors and calls no allocator. Use `-no-strings` to omit names. + +`j1939_db_find` looks up a CAN ID/PGN; `j1939_signal_by_spn` searches the sorted +SPN index across the database. `BA_ "SPN"` attributes supply SPN numbers (0 when +absent). `j1939_signal_by_name` searches one message, and +`j1939_messages_by_name` returns all matching messages. Multiplex alternatives +are retained, including those sharing a start bit; use `j1939_signal_active` +before decoding one. Extended multiplex ranges (`SG_MUL_VAL_`) and nested +switch selection are not implemented. + +##### Portable message accessors + +```bash +bin/dbc_compiler -in input.dbc -accessor_path payloads.h +``` + +This optional standalone C11/C++14 header emits explicit byte shifts and masks +for each signal, including mixed Intel/Motorola messages and multiplex alternatives. +There is no aggregate message union or runtime library dependency. Names use +`j1939___` followed by `_raw`, `_store_raw`, +or `_phys`. Raw stores preserve all other payload bits. `_phys` applies signed +interpretation, scale and offset; stores take raw wire values. Byte-aligned Intel +signals wider than 64 bits get `_get_bytes` and `_set_bytes` instead. +`VAL_` labels become prefixed `UINT64_C` defines; punctuation becomes underscores, +and colliding labels receive a numeric suffix. + +By default all accessors are available. To include only selected messages, define +`J1939_ACCESSORS_SELECT` and `J1939_ACCESSORS__` before +including the header. Provide a payload at least as large as the message DLC. +Accessors read or write the named bits directly; the caller selects the active +multiplex alternative and sets the switch separately. + +##### PGN format (C++ host tools) +This format produces a single file where **all input DBC files** are compiled into one `std::map`: ```c++ std::map j1939_dbc = { . . . }; ``` +The map, strings, vectors, and enum maps allocate during initialization. Use the +plain-C database for allocation-free embedded lookup. + The `J1939` class uses this map to decode/encode arbitrary CAN frames (see `can_sandbox.cpp` for details). Note: by default, the name of the first input DBC file is used to build the map name (e.g., `j1939.dbc` → `j1939_dbc`). This can be overridden with the `-name` command-line option. -##### Union format -The second format packs a byte buffer and a bitfield struct into an unnamed union, which is saved to a header file. +##### Legacy union format +This legacy format packs a byte buffer and a bitfield struct into an unnamed union, which is saved to a header file. *Note: a single header file is generated for all listed input DBC files.* ```c++ #define CTLEGO_MESSAGE_ID 0x8c210253 @@ -142,25 +187,25 @@ struct ctlego_message_t { union { uint8_t data[CTLEGO_MESSAGE_DLC]; struct { - uint16_t VehicleSpeed : 16; - uint8_t ControlEngine : 1; - uint16_t YawRate : 16; - uint8_t TransCurrentGear : 8; + uint64_t vehicle_speed : 16; + uint64_t control_engine : 1; + uint64_t yaw_rate : 16; + uint64_t trans_current_gear : 8; } fields __attribute__((packed)); }; #ifdef __cplusplus - double vehicle_speed() const { return fields.VehicleSpeed * 0.001 + 0; } - void vehicle_speed(double value) { fields.VehicleSpeed = (value - 0) / 0.001; } + double vehicle_speed() const { return fields.vehicle_speed * 0.001 + 0; } + void vehicle_speed(double value) { fields.vehicle_speed = (value - 0) / 0.001; } - uint8_t control_engine() const { return fields.ControlEngine; } - void control_engine(uint8_t value) { fields.ControlEngine = value; } + uint8_t control_engine() const { return fields.control_engine; } + void control_engine(uint8_t value) { fields.control_engine = value; } - double yaw_rate() const { return fields.YawRate * 0.00012207 + -3.92; } - void yaw_rate(double value) { fields.YawRate = (value - -3.92) / 0.00012207; } + double yaw_rate() const { return fields.yaw_rate * 0.00012207 + -3.92; } + void yaw_rate(double value) { fields.yaw_rate = (value - -3.92) / 0.00012207; } - double trans_current_gear() const { return fields.TransCurrentGear * 1 + -125; } - void trans_current_gear(double value) { fields.TransCurrentGear = (value - -125) / 1; } + double trans_current_gear() const { return fields.trans_current_gear * 1 + -125; } + void trans_current_gear(double value) { fields.trans_current_gear = (value - -125) / 1; } void fillFrameWith(uint8_t value = 0xFF) { memset(data, value, sizeof(data)); } #endif @@ -187,5 +232,7 @@ struct all_xyz_messages_t { ``` *Note: the name of that union is taken from the first input DBC file's name (e.g., `xyz_messages.dbc` → `all_xyz_messages_t`).* +*Portability:* `fields` is a compiler-specific bitfield layout. C and C++ leave the allocation order of bitfields, the storage unit they pack into, and whether a bitfield may cross that unit up to the implementation. This output uses `uint64_t` and `int64_t` bitfields, anonymous padding whose widths follow the DBC start bits, and `__attribute__((packed))` (GCC and Clang). Motorola (`@0`) signals are emitted by walking start bits from the end of the payload. A message that mixes `@0` and `@1` is rejected. The `data[]` / `fields` overlay, and the `all_*` union of every message, follows that compiler's bitfield rules. The portable lookup table is the plain-C database from `dbc_compiler -c_path`: const structs, with the bytes read and written by `j1939_db.c`. + ## License This project is licensed under the MIT License -- see [LICENSE](LICENSE) for details. diff --git a/dbc_compiler/dbc_compiler.cpp b/dbc_compiler/dbc_compiler.cpp index f11fb86..e374841 100644 --- a/dbc_compiler/dbc_compiler.cpp +++ b/dbc_compiler/dbc_compiler.cpp @@ -25,6 +25,7 @@ int main(int argc, const char* argv[]) { std::vector inputs; std::string pgn_path; std::string union_path; + std::string accessor_path; std::string c_path; std::string var_name; bool no_strings = false; @@ -33,6 +34,7 @@ int main(int argc, const char* argv[]) { options.addOption("-name", "Defines variable name in the output files. By default, the first input DBC name will be used.", &var_name); options.addOption("-pgn_path", "Full path of the output file to store the DBC content in PGN format.", &pgn_path); options.addOption("-union_path", "Full path of the output file to store the DBC content in the 'union' format.", &union_path); + options.addOption("-accessor_path", "Standalone portable C/C++ payload accessors (header).", &accessor_path); options.addOption("-c_path", "Full path of the generated plain-C database (.c). A matching .h is written beside it.", &c_path); options.addOption("-no-strings", "Omit signal and message names from the plain-C database.", &no_strings); @@ -40,7 +42,7 @@ int main(int argc, const char* argv[]) { return 1; } - if (inputs.size() == 0 || (union_path.empty() && pgn_path.empty() && c_path.empty())) { + if (inputs.size() == 0 || (union_path.empty() && pgn_path.empty() && c_path.empty() && accessor_path.empty())) { printf( "Usage: dbc_compiler \n"); printf( " where could be:\n"); options.print(); @@ -84,6 +86,17 @@ int main(int argc, const char* argv[]) { h_file << h_text.str(); } + if (!accessor_path.empty()) { + std::ostringstream text; + std::string error; + if (!parser.generateAccessorOutput(text, error)) { + std::cerr << error << std::endl; + return 4; + } + auto file = getFile(accessor_path); + *file << text.str(); + } + // TODO: add option to disable the following step. parser.removeDuplicates(); diff --git a/j1939_parser/dbc_parser/dbc_accessors.cpp b/j1939_parser/dbc_parser/dbc_accessors.cpp new file mode 100644 index 0000000..3c74daa --- /dev/null +++ b/j1939_parser/dbc_parser/dbc_accessors.cpp @@ -0,0 +1,96 @@ +#include "dbc_parser.h" + +#include +#include +#include + +namespace { +std::string identifier(const std::string &text) { + std::string result; + for (unsigned char c : text) result += std::isalnum(c) ? char(c) : '_'; + return result; +} +} + +bool DbcParser::generateAccessorOutput(std::ostream &out, std::string &error) const { + std::ostringstream code; + code << "/* Generated portable payload accessors. No bitfield ABI or runtime library. */\n" + << "#include \n#include \n"; + for (const auto &entry : raw_messages_) { + const auto &msg = entry.second; + const std::string prefix = "j1939_" + identifier(msg.name()) + "_" + std::to_string(entry.first); + const std::string select = "J1939_ACCESSORS_" + identifier(msg.name()) + "_" + std::to_string(entry.first); + code << "\n#if !defined(J1939_ACCESSORS_SELECT) || defined(" << select << ")\n" + << "#ifndef " << select << "_DEFINED\n#define " << select << "_DEFINED\n" + << "#define " << prefix << "_CAN_ID " << entry.first << "u\n" + << "#define " << prefix << "_DLC " << msg.dlc() << "u\n"; + std::set names; + for (const auto &sig : msg.allSignals()) { + std::string name = prefix + "_" + identifier(sig.name()); + if (!names.insert(name).second) { + error = "accessor identifier collision: " + name; + return false; + } + std::vector bits; + int bit = sig.startBit(); + for (unsigned i = 0; i < sig.bitLength(); ++i) { + if (bit < 0 || bit >= msg.dlc() * 8) { + error = "accessor signal outside payload: " + sig.name(); + return false; + } + bits.push_back(static_cast(bit)); + bit = sig.little_endian() ? bit + 1 : (bit % 8 == 0 ? bit + 15 : bit - 1); + } + if (bits.empty()) { + error = "accessor signal has zero length: " + sig.name(); + return false; + } + if (bits.size() > 64) { + if (!sig.little_endian() || sig.startBit() % 8 || bits.size() % 8) { + error = "accessor byte string must be byte aligned and little endian: " + sig.name(); + return false; + } + code << "static inline void " << name << "_get_bytes(const uint8_t *payload, uint8_t *value) { memcpy(value, payload + " + << sig.startBit() / 8 << ", " << bits.size() / 8 << "); }\n" + << "static inline void " << name << "_set_bytes(uint8_t *payload, const uint8_t *value) { memcpy(payload + " + << sig.startBit() / 8 << ", value, " << bits.size() / 8 << "); }\n"; + continue; + } + code << "static inline uint64_t " << name << "_raw(const uint8_t *payload) {\n uint64_t value = 0;\n"; + for (unsigned i = 0; i < bits.size(); ++i) { + const unsigned shift = sig.little_endian() ? i : bits.size() - 1 - i; + code << " value |= (uint64_t)((payload[" << bits[i] / 8 << "] >> " << bits[i] % 8 + << ") & 1u) << " << shift << ";\n"; + } + code << " return value;\n}\n" + << "static inline void " << name << "_store_raw(uint8_t *payload, uint64_t value) {\n"; + for (unsigned i = 0; i < bits.size(); ++i) { + const unsigned shift = sig.little_endian() ? i : bits.size() - 1 - i; + code << " payload[" << bits[i] / 8 << "] = (uint8_t)((payload[" << bits[i] / 8 << "] & " + << (255u ^ (1u << (bits[i] % 8))) << "u) | (((value >> " << shift << ") & 1u) << " << bits[i] % 8 << "));\n"; + } + code << "}\nstatic inline double " << name << "_phys(const uint8_t *payload) {\n uint64_t raw = " << name << "_raw(payload);\n"; + if (sig.isSigned()) { + code << " double value = (raw & (UINT64_C(1) << " << bits.size() - 1 + << ")) ? (double)(-1 - (int64_t)(~raw & UINT64_C(" << make_mask(bits.size()) + << "))) : (double)raw;\n"; + } else { + code << " double value = (double)raw;\n"; + } + code << " return value * (" << sig.scaleLiteral() << ") + (" << sig.offsetLiteral() << ");\n}\n"; + std::set labels; + for (const auto &label : sig.enums()) { + std::string id = name + "_" + identifier(label.second.substr(1, label.second.size() - 2)); + if (!labels.insert(id).second) id += "_" + std::to_string(label.first); + if (!names.insert(id).second) { + error = "accessor enum identifier collision: " + id; + return false; + } + code << "#define " << id << " UINT64_C(" << label.first << ")\n"; + } + } + code << "#endif\n#endif\n"; + } + out << code.str(); + return true; +} diff --git a/j1939_parser/dbc_parser/dbc_c_gen_tests.cpp b/j1939_parser/dbc_parser/dbc_c_gen_tests.cpp index 84a3eae..52d3832 100644 --- a/j1939_parser/dbc_parser/dbc_c_gen_tests.cpp +++ b/j1939_parser/dbc_parser/dbc_c_gen_tests.cpp @@ -636,3 +636,85 @@ TEST_F(DbcCGenTest, GeneratedCCompiles) { ADD_FAILURE() << got.str(); } } + +TEST_F(DbcCGenTest, PortableAccessorsCompileAndRunInCAndCpp) { + DbcParser parser; + ASSERT_TRUE(parser.parseFile(writeTemp( + "BO_ 100 Mixed: 16 X\n" + " SG_ Intel : 3|13@1+ (0.5,-2) [0|4093] \"\" X\n" + " SG_ Motorola : 23|12@0- (1,0) [-2048|2047] \"\" X\n" + " SG_ Wide : 32|64@1- (1,0) [0|0] \"\" X\n" + " SG_ Switch M : 96|8@1+ (1,0) [0|255] \"\" X\n" + " SG_ A m0 : 104|8@1+ (1,0) [0|255] \"\" X\n" + " SG_ B m1 : 104|8@1+ (1,0) [0|255] \"\" X\n" + "\nBO_ 101 Omitted: 1 X\n SG_ Other : 0|8@1+ (1,0) [0|255] \"\" X\n" + "\nBO_ 102 Bytes: 10 X\n SG_ Text : 0|80@1+ (1,0) [0|0] \"\" X\n" + "\nVAL_ 100 Intel 3 \"Three\" 4 \"On-Off\" 5 \"On Off\" ;\n"))); + std::ostringstream header; + std::string error; + ASSERT_TRUE(parser.generateAccessorOutput(header, error)) << error; + EXPECT_EQ(header.str().find("__attribute__"), std::string::npos); + EXPECT_EQ(header.str().find("union"), std::string::npos); + std::string source = + "#define J1939_ACCESSORS_SELECT\n#define J1939_ACCESSORS_Mixed_100\n#define J1939_ACCESSORS_Bytes_102\n" + header.str() + + "\n#ifdef j1939_Omitted_101_DLC\n#error Message selection failed\n#endif\n" + "#include \nint main(void) {\n" + "uint8_t p[16]; memset(p, 255, sizeof(p));\n" + "j1939_Mixed_100_Intel_store_raw(p, 0x1234);\n" + "assert(p[0] == 0xa7 && p[1] == 0x91 && p[2] == 255);\n" + "assert(j1939_Mixed_100_Intel_raw(p) == 0x1234);\n" + "assert(j1939_Mixed_100_Intel_phys(p) == 2328);\n" + "assert(j1939_Mixed_100_Intel_Three == 3);\n" + "assert(j1939_Mixed_100_Intel_On_Off == 4);\n" + "assert(j1939_Mixed_100_Intel_On_Off_5 == 5);\n" + "j1939_Mixed_100_Motorola_store_raw(p, 0xabc);\n" + "assert(p[2] == 0xab && p[3] == 0xcf);\n" + "assert(j1939_Mixed_100_Motorola_raw(p) == 0xabc);\n" + "assert(j1939_Mixed_100_Motorola_phys(p) == -1348);\n" + "j1939_Mixed_100_Wide_store_raw(p, UINT64_C(0x8000000000000000));\n" + "assert(j1939_Mixed_100_Wide_raw(p) == UINT64_C(0x8000000000000000));\n" + "assert(j1939_Mixed_100_Wide_phys(p) == -9223372036854775808.0);\n" + "j1939_Mixed_100_A_store_raw(p, 42);\n" + "assert(j1939_Mixed_100_B_raw(p) == 42);\n" + "uint8_t text[10] = {1,2,3,4,5,6,7,8,9,10}, copy[10];\n" + "j1939_Bytes_102_Text_set_bytes(p, text);\n" + "j1939_Bytes_102_Text_get_bytes(p, copy);\n" + "assert(memcmp(text, copy, 10) == 0);\nreturn 0; }\n"; + std::string path = writeTemp(source); + for (const std::string &compiler : {"cc -x c -std=c11", "c++ -x c++ -std=c++14"}) { + std::string binary = path + ".bin"; + temp_paths_.push_back(binary); + ASSERT_EQ(system((compiler + " -Wall -Wextra -Werror -pedantic '" + path + "' -o '" + binary + "'").c_str()), 0); + EXPECT_EQ(system(("'" + binary + "'").c_str()), 0); + } +} + +TEST_F(DbcCGenTest, AccessorsRejectInvalidLayoutWithoutPartialOutput) { + DbcParser parser; + ASSERT_TRUE(parser.parseFile(writeTemp("BO_ 100 Bad: 1 X\n SG_ TooWide : 7|16@0+ (1,0) [0|0] \"\" X\n\n"))); + std::ostringstream out; + std::string error; + EXPECT_FALSE(parser.generateAccessorOutput(out, error)); + EXPECT_TRUE(out.str().empty()); + EXPECT_FALSE(error.empty()); +} + +TEST_F(DbcCGenTest, AccessorsRejectZeroLengthUnalignedBytesAndIdentifierCollisions) { + const std::vector cases{ + " SG_ Empty : 0|0@1+ (1,0) [0|0] \"\" X\n", + " SG_ Text : 1|80@1+ (1,0) [0|0] \"\" X\n", + " SG_ Text : 0|81@1+ (1,0) [0|0] \"\" X\n", + " SG_ Text : 7|80@0+ (1,0) [0|0] \"\" X\n", + " SG_ Same : 0|8@1+ (1,0) [0|0] \"\" X\n SG_ Same : 8|8@1+ (1,0) [0|0] \"\" X\n", + " SG_ A : 0|8@1+ (1,0) [0|0] \"\" X\n SG_ A_Label : 8|8@1+ (1,0) [0|0] \"\" X\n\nVAL_ 100 A 1 \"Label\" ;\n" + }; + for (const auto &signals : cases) { + DbcParser parser; + ASSERT_TRUE(parser.parseFile(writeTemp("BO_ 100 Bad: 16 X\n" + signals + "\n"))); + std::ostringstream out; + std::string error; + EXPECT_FALSE(parser.generateAccessorOutput(out, error)) << signals; + EXPECT_TRUE(out.str().empty()); + EXPECT_FALSE(error.empty()); + } +} diff --git a/j1939_parser/dbc_parser/dbc_parser.h b/j1939_parser/dbc_parser/dbc_parser.h index 79347da..b005cd9 100644 --- a/j1939_parser/dbc_parser/dbc_parser.h +++ b/j1939_parser/dbc_parser/dbc_parser.h @@ -70,6 +70,9 @@ class DbcParser { // Outputs the raw_messages content into the provided stream as union of a packed structure and a bytes array. void generateUnionOutput(std::ofstream *out) const; + // Portable, standalone per-message C/C++ payload accessors. + bool generateAccessorOutput(std::ostream &out, std::string &error) const; + // Writes a plain-C const database (j1939_db.h layout) to the two streams. // Uses the messages as parsed, before removeDuplicates(). On failure nothing // is written and `error` explains the collapse or signal problem.