Compare commits

...
2 Commits
Author SHA1 Message Date
Admin fff7aef968 vm 模块注释完善:Doxygen 风格。
- Image.h/.cpp:头 104 布局逐字段、SHA-256 增量状态机(update/process/final)、
  校验项清单(from)、型号标识契约、func_row/const_entry/data_len 等访问器语义
- Machine.h/.cpp:Fault 枚举逐项、create 校验顺序(解析→SHA→型号)、
  调用约定(r0 结果/r1..r7 实参)、exec_one 取指/计数/分发流程、
  do_call/do_ret 帧语义、do_cal 八 FB 字段布局、slot_get/set 边界契约
2026-08-21 23:21:51 +08:00
Admin 96607cfe75 isa 模块注释完善:Doxygen 风格。
- Types.h:定宽类型、TypeTag、饱和四则的 @brief/@param/@return
- Op.h:Op 枚举冻结约束、OpFormat/OpClass、OpDef/kOpDefs 表、三个查询函数
- Instr.h:指令字布局、pack/拆字段、按形态 enc_* 系列
- Encode.h/.cpp:Decoded 字段语义、encode/decode/disasm 契约
2026-08-21 23:19:08 +08:00
9 changed files with 578 additions and 130 deletions
+30 -7
View File
@@ -1,6 +1,7 @@
/** /**
* @file Encode.h * @file Encode.h
* @brief 指令编解码与反汇编 * @brief 指令编解码与反汇编
* @details 给 STCompiler --disasm 与测试往返使用;文本格式见 Doc/isa/指令与映像.md。
* @author * @author
* @date 2026-08-19 * @date 2026-08-19
*/ */
@@ -14,18 +15,40 @@
#include "isa/Op.h" #include "isa/Op.h"
namespace isa { namespace isa {
// 解码后的字段视图 /**
* @brief 解码后的字段视图。
* @details 各字段是 8 位原始值,含义按操作数形态(OpFormat)解释,
* a|b 可用 imm16 / off16 组合成 16 位视图。
*/
struct Decoded { struct Decoded {
Op op; Op op; ///< 操作码
uint8_t rd; uint8_t rd; ///< 目标寄存器 / 条件寄存器
uint8_t a; uint8_t a; ///< 源寄存器 / 立即数低 8 位 / 偏移低 8 位
uint8_t b; uint8_t b; ///< 源寄存器 / 立即数高 8 位 / 偏移高 8 位
}; };
// 编解码往返:encode(decode(w)) == w /**
* @brief 编码:字段视图打包成一条 32 位指令字。
* @param d 解码后的字段视图
* @return 打包后的指令字;满足 encode(decode(w)) == w
*/
Instr encode(Decoded d); Instr encode(Decoded d);
/**
* @brief 解码:指令字拆成字段视图。
* @param w 32 位指令字
* @return 各字段视图
*/
Decoded decode(Instr w); Decoded decode(Instr w);
// 反汇编一行文本,写入 out,至多 cap 字节(含 '\0')。格式见 Doc/isa/指令与映像.md。 /**
* @brief 反汇编一条指令为一行文本。
* @param w 指令字
* @param out 输出缓冲
* @param cap 缓冲容量(含 '\0');cap==0 时直接返回、不写 out
* @details 按操作数形态表驱动输出(如 `RET`、`MOVE r1, r2`、`LOADK r0, 3`、
* `ADD r1, r2, r3`、`JMP +4`、`JT r0, -1`、`CALL 1`、`CAL_TON 0`);
* 未知操作码输出 `??? 0x<w>`。
*/
void disasm(Instr w, char* out, size_t cap); void disasm(Instr w, char* out, size_t cap);
} }
+95 -13
View File
@@ -1,6 +1,8 @@
/** /**
* @file Instr.h * @file Instr.h
* @brief 32-bit 指令打包 / 拆字段 * @brief 32-bit 指令打包 / 拆字段
* @details 指令字布局:`[ op:8 | rd:8 | a:8 | b:8 ]`,整体是一个小端 uint32_t。
* 字段含义按操作码形态解释,见 Doc/isa/指令与映像.md。
* @author * @author
* @date 2026-08-19 * @date 2026-08-19
*/ */
@@ -12,11 +14,17 @@
#include "isa/Op.h" #include "isa/Op.h"
namespace isa { namespace isa {
// 指令字:[ op:8 | rd:8 | a:8 | b:8 ]整体是一个小端 uint32_t。 /// 指令字:`[ op:8 | rd:8 | a:8 | b:8 ]`,小端 uint32_t。
// 字段含义按操作码形态解释,见 Doc/isa/指令与映像.md。
typedef uint32_t Instr; typedef uint32_t Instr;
// 打包 / 拆字段 /**
* @brief 打包:四个字段拼成一条指令字。
* @param op 操作码(低 8 位)
* @param rd 目标寄存器 / 条件寄存器(第 8..15 位)
* @param a 源寄存器 / 立即数低 8 位 / 偏移低 8 位(第 16..23 位)
* @param b 源寄存器 / 立即数高 8 位 / 偏移高 8 位(第 24..31 位)
* @return 打包后的指令字
*/
inline Instr pack(Op op, uint8_t rd, uint8_t a, uint8_t b) { inline Instr pack(Op op, uint8_t rd, uint8_t a, uint8_t b) {
return static_cast<uint32_t>(static_cast<uint8_t>(op)) return static_cast<uint32_t>(static_cast<uint8_t>(op))
| (static_cast<uint32_t>(rd) << 8) | (static_cast<uint32_t>(rd) << 8)
@@ -24,69 +32,143 @@ namespace isa {
| (static_cast<uint32_t>(b) << 24); | (static_cast<uint32_t>(b) << 24);
} }
/**
* @brief 取操作码。
* @param w 指令字
* @return 低 8 位解释为 Op
*/
inline Op op(Instr w) { inline Op op(Instr w) {
return static_cast<Op>(w & 0xFFu); return static_cast<Op>(w & 0xFFu);
} }
/**
* @brief 取目标寄存器字段。
* @param w 指令字
* @return rd(第 8..15 位)
*/
inline uint8_t rd(Instr w) { inline uint8_t rd(Instr w) {
return static_cast<uint8_t>((w >> 8) & 0xFFu); return static_cast<uint8_t>((w >> 8) & 0xFFu);
} }
/**
* @brief 取 a 字段。
* @param w 指令字
* @return a(第 16..23 位)
*/
inline uint8_t a(Instr w) { inline uint8_t a(Instr w) {
return static_cast<uint8_t>((w >> 16) & 0xFFu); return static_cast<uint8_t>((w >> 16) & 0xFFu);
} }
/**
* @brief 取 b 字段。
* @param w 指令字
* @return b(第 24..31 位)
*/
inline uint8_t b(Instr w) { inline uint8_t b(Instr w) {
return static_cast<uint8_t>((w >> 24) & 0xFFu); return static_cast<uint8_t>((w >> 24) & 0xFFu);
} }
// 组合视图:a|b 拼成 16 位(const_id / fn_id / slot /**
* @brief 组合视图:a|b 拼成 16 位无符号数。
* @param w 指令字
* @return 小端拼出的 16 位值,用作 const_id / fn_id / slot 号
*/
inline uint16_t imm16(Instr w) { inline uint16_t imm16(Instr w) {
return static_cast<uint16_t>(a(w) | (static_cast<uint16_t>(b(w)) << 8)); return static_cast<uint16_t>(a(w) | (static_cast<uint16_t>(b(w)) << 8));
} }
// 组合视图:a|b 为有符号相对偏移,单位是指令条数 /**
* @brief 组合视图:a|b 为有符号相对偏移。
* @param w 指令字
* @return 偏移量,单位是指令条数(跳转目标 = 下一条指令 + off)
*/
inline int16_t off16(Instr w) { inline int16_t off16(Instr w) {
return static_cast<int16_t>(imm16(w)); return static_cast<int16_t>(imm16(w));
} }
// 按形态的便捷编码 /**
* @brief 按 RR 形态编码。
* @param op 操作码(MOVE / NOT
* @param rd 目标寄存器
* @param rs 源寄存器(放进 a
* @return 指令字
*/
inline Instr enc_rr(Op op, uint8_t rd, uint8_t rs) { inline Instr enc_rr(Op op, uint8_t rd, uint8_t rs) {
return pack(op, rd, rs, 0); // MOVE / NOTa = rs return pack(op, rd, rs, 0);
} }
/**
* @brief 按 RRR 形态编码。
* @param op 操作码(AND/OR/ADD/.../CMP_xx
* @param rd 目标寄存器
* @param ra 第一源寄存器
* @param rb 第二源寄存器
* @return 指令字
*/
inline Instr enc_rrr(Op op, uint8_t rd, uint8_t ra, uint8_t rb) { inline Instr enc_rrr(Op op, uint8_t rd, uint8_t ra, uint8_t rb) {
return pack(op, rd, ra, rb); // AND/OR/ADD/.../CMP_xx return pack(op, rd, ra, rb);
} }
/**
* @brief 按 IMM 形态编码。
* @param op 操作码(LOADK
* @param rd 目标寄存器
* @param imm 16 位立即数(const_id),拆成 a|b 存放
* @return 指令字
*/
inline Instr enc_imm(Op op, uint8_t rd, uint16_t imm) { inline Instr enc_imm(Op op, uint8_t rd, uint16_t imm) {
return pack(op, rd, static_cast<uint8_t>(imm & 0xFFu), return pack(op, rd, static_cast<uint8_t>(imm & 0xFFu),
static_cast<uint8_t>((imm >> 8) & 0xFFu)); // LOADK static_cast<uint8_t>((imm >> 8) & 0xFFu));
} }
/**
* @brief 按 JMP 形态编码。
* @param off 有符号相对偏移(条数),拆成 a|b 存放
* @return 指令字
*/
inline Instr enc_jmp(int16_t off) { inline Instr enc_jmp(int16_t off) {
return pack(Op::JMP, 0, return pack(Op::JMP, 0,
static_cast<uint8_t>(static_cast<uint16_t>(off) & 0xFFu), static_cast<uint8_t>(static_cast<uint16_t>(off) & 0xFFu),
static_cast<uint8_t>((static_cast<uint16_t>(off) >> 8) & 0xFFu)); static_cast<uint8_t>((static_cast<uint16_t>(off) >> 8) & 0xFFu));
} }
/**
* @brief 按 JC 形态编码(条件跳转)。
* @param op 操作码(JT / JF
* @param r 条件寄存器(放进 rd
* @param off 有符号相对偏移(条数),放进 a|b
* @return 指令字
*/
inline Instr enc_jc(Op op, uint8_t r, int16_t off) { inline Instr enc_jc(Op op, uint8_t r, int16_t off) {
// JT / JF:条件寄存器在 rd,偏移在 a|b
return pack(op, r, return pack(op, r,
static_cast<uint8_t>(static_cast<uint16_t>(off) & 0xFFu), static_cast<uint8_t>(static_cast<uint16_t>(off) & 0xFFu),
static_cast<uint8_t>((static_cast<uint16_t>(off) >> 8) & 0xFFu)); static_cast<uint8_t>((static_cast<uint16_t>(off) >> 8) & 0xFFu));
} }
/**
* @brief 按 SLOT 形态编码。
* @param op 操作码(LOAD_I / STORE_Q / LOAD_M / STORE_M / LOAD_GLOBAL / STORE_GLOBAL / CAL_*
* @param rd 目标寄存器(CAL_* 时置 0)
* @param slot 槽号 / 实例号,放进 a|b
* @return 指令字
*/
inline Instr enc_slot(Op op, uint8_t rd, uint16_t slot) { inline Instr enc_slot(Op op, uint8_t rd, uint16_t slot) {
// LOAD_I / STORE_Q / LOAD_M / STORE_M / LOAD_GLOBAL / STORE_GLOBAL / CAL_*
// 槽号 / 实例号在 a|b
return enc_imm(op, rd, slot); return enc_imm(op, rd, slot);
} }
/**
* @brief 按 CALL 形态编码。
* @param fn_id 函数表下标,放进 a|b
* @return 指令字
*/
inline Instr enc_call(uint16_t fn_id) { inline Instr enc_call(uint16_t fn_id) {
return enc_imm(Op::CALL, 0, fn_id); return enc_imm(Op::CALL, 0, fn_id);
} }
/**
* @brief 按 NONE 形态编码(RET)。
* @return 指令字
*/
inline Instr enc_ret() { inline Instr enc_ret() {
return pack(Op::RET, 0, 0, 0); return pack(Op::RET, 0, 0, 0);
} }
+42 -11
View File
@@ -1,6 +1,8 @@
/** /**
* @file Op.h * @file Op.h
* @brief 操作码枚举 + 助记符 * @brief 操作码枚举、操作数形态与编译期指令表
* @details 操作码数值即 .stb 指令编码。执行器(vm)只依赖本表;
* 编译器侧的登记见 Doc/isa/指令配置.mdcompiler/machine.toml,与之强校验)。
* @author * @author
* @date 2026-08-19 * @date 2026-08-19
*/ */
@@ -10,8 +12,11 @@
#include <cstdint> #include <cstdint>
namespace isa { namespace isa {
// 操作码一次列全。数值即编码:冻结后不得改顺序、不得插值, /**
// 增加指令只能追加到末尾,并同步 Doc/isa/指令与映像.md 与测试 * @brief 操作码枚举
* @details 数值即编码:冻结后不得改顺序、不得插值,增加指令只能追加到末尾,
* 并同步 Doc/isa/指令与映像.md、compiler/machine.toml 与测试。
*/
enum class Op : uint8_t { enum class Op : uint8_t {
MOVE = 0, // MOVE rd, rs MOVE = 0, // MOVE rd, rs
LOADK = 1, // LOADK rd, const_id LOADK = 1, // LOADK rd, const_id
@@ -50,10 +55,13 @@ namespace isa {
RET = 33, // RET RET = 33, // RET
}; };
// 操作码总数 /// 操作码总数= 最大 opcode + 1kOpDefs 的下标上界)。
static const int kOpCount = 34; static const int kOpCount = 34;
// 操作数形态(三层分类第二层,见 Doc/isa/指令配置.md /**
* @brief 操作数形态(三层分类第二层,见 Doc/isa/指令配置.md)。
* @details 决定操作数 a|b 的解释方式与反汇编文本格式。
*/
enum class OpFormat : uint8_t { enum class OpFormat : uint8_t {
RR, // 两寄存器:rd rsMOVE / NOT RR, // 两寄存器:rd rsMOVE / NOT
RRR, // 三寄存器:rd ra rb(逻辑 / 算术 / 比较) RRR, // 三寄存器:rd ra rb(逻辑 / 算术 / 比较)
@@ -66,19 +74,28 @@ namespace isa {
NONE, // 无操作数(RET NONE, // 无操作数(RET
}; };
// 操作对象大类(三层分类第一层) /**
* @brief 操作对象大类(三层分类第一层)。
*/
enum class OpClass : uint8_t { enum class OpClass : uint8_t {
Plain, // 无实例:寄存器 / 立即数 / 槽 / 分支 / 调用 Plain, // 无实例:寄存器 / 立即数 / 槽 / 分支 / 调用
Instance, // 有实例:操作数据区实例块(内建 FB) Instance, // 有实例:操作数据区实例块(内建 FB)
}; };
// 编译期指令表:下标与 Op 数值一一对应(ops.txt 强校验的基准) /**
* @brief 编译期指令表条目。
* @details 一条指令的名称、操作数形态与大类;下标与 Op 数值一一对应。
*/
struct OpDef { struct OpDef {
const char* name; const char* name; ///< 助记符(与 .stb / machine.toml 一致)
OpFormat format; OpFormat format; ///< 操作数形态
OpClass cls; OpClass cls; ///< 操作对象大类
}; };
/**
* @brief 编译期指令表:下标与 Op 数值一一对应(machine.toml 强校验的基准)。
* @details 表与 Op 枚举同步维护;查询入口见 mnemonic / format / op_class。
*/
static const OpDef kOpDefs[kOpCount] = { static const OpDef kOpDefs[kOpCount] = {
{"MOVE", OpFormat::RR, OpClass::Plain}, // 0 {"MOVE", OpFormat::RR, OpClass::Plain}, // 0
{"LOADK", OpFormat::IMM, OpClass::Plain}, // 1 {"LOADK", OpFormat::IMM, OpClass::Plain}, // 1
@@ -116,17 +133,31 @@ namespace isa {
{"RET", OpFormat::NONE, OpClass::Plain}, // 33 {"RET", OpFormat::NONE, OpClass::Plain}, // 33
}; };
// 助记符 / 格式 / 大类:查表(越界返回哨兵) /**
* @brief 查助记符。
* @param op 操作码
* @return 对应助记符;越界返回哨兵 "???"
*/
inline const char* mnemonic(Op op) { inline const char* mnemonic(Op op) {
const int idx = static_cast<int>(op); const int idx = static_cast<int>(op);
return (idx >= 0 && idx < kOpCount) ? kOpDefs[idx].name : "???"; return (idx >= 0 && idx < kOpCount) ? kOpDefs[idx].name : "???";
} }
/**
* @brief 查操作数形态。
* @param op 操作码
* @return 对应 OpFormat;越界返回 OpFormat::NONE
*/
inline OpFormat format(Op op) { inline OpFormat format(Op op) {
const int idx = static_cast<int>(op); const int idx = static_cast<int>(op);
return (idx >= 0 && idx < kOpCount) ? kOpDefs[idx].format : OpFormat::NONE; return (idx >= 0 && idx < kOpCount) ? kOpDefs[idx].format : OpFormat::NONE;
} }
/**
* @brief 查操作对象大类。
* @param op 操作码
* @return 对应 OpClass;越界返回 OpClass::Plain
*/
inline OpClass op_class(Op op) { inline OpClass op_class(Op op) {
const int idx = static_cast<int>(op); const int idx = static_cast<int>(op);
return (idx >= 0 && idx < kOpCount) ? kOpDefs[idx].cls : OpClass::Plain; return (idx >= 0 && idx < kOpCount) ? kOpDefs[idx].cls : OpClass::Plain;
+51 -10
View File
@@ -1,6 +1,8 @@
/** /**
* @file Types.h * @file Types.h
* @brief 类型定义 * @brief 定宽类型与饱和算术
* @details 虚拟机字长与类型契约的唯一来源。compiler 与 vm 共用同一套规则,
* 详见 Doc/isa/指令与映像.md。
* @author * @author
* @date 2026-08-18 * @date 2026-08-18
*/ */
@@ -12,15 +14,28 @@
namespace isa { namespace isa {
namespace types { namespace types {
// 定宽类型。整数溢出规则:饱和(夹到 INT 最小/最大), /**
// 由 compiler 与 vm 按同一规则实现,见 Doc/isa/指令与映像.md * @brief 布尔值:8 位,只允许 0/10=FALSE1=TRUE
using BOOL = uint8_t; // 只允许 0/1 */
using INT = int16_t; // IEC INT using BOOL = uint8_t;
// 毫秒,有符号。64 位理由见 Doc/isa/指令与映像.md
// 差值可负、为 DATE_AND_TIME 与 64 位定时器预留。槽位按 8 字节对齐。 /**
* @brief IEC INT:16 位有符号整数,溢出按饱和规则处理。
*/
using INT = int16_t;
/**
* @brief 时间:64 位有符号整数,单位毫秒。
* @details 取 64 位的理由见 Doc/isa/指令与映像.md:差值可负、
* 为 DATE_AND_TIME 与 64 位定时器预留。槽位按 8 字节对齐。
*/
using TIME = int64_t; using TIME = int64_t;
// 槽 / 常量表类型标记,数值冻结:0=BOOL、1=INT、2=TIME(见映像规范) /**
* @brief 槽 / 常量表类型标记。
* @details 数值冻结并写入 .stb 常量表:0=BOOL、1=INT、2=TIME(见映像规范),
* 不得改顺序、不得插值。
*/
enum TypeTag : uint8_t { enum TypeTag : uint8_t {
Bool = 0, Bool = 0,
Int = 1, Int = 1,
@@ -29,6 +44,13 @@ namespace isa {
// 饱和算术:夹到 INT 最小/最大,编译期与 VM 共用同一规则。 // 饱和算术:夹到 INT 最小/最大,编译期与 VM 共用同一规则。
/**
* @brief 饱和加法。
* @param a 加数
* @param b 加数
* @return a+b,超出 INT 范围时夹到最小/最大值
* @details 中间量用 int32 计算,避免 int16 溢出未定义行为。
*/
inline INT sat_add(INT a, INT b) { inline INT sat_add(INT a, INT b) {
const int32_t sum = static_cast<int32_t>(a) + static_cast<int32_t>(b); const int32_t sum = static_cast<int32_t>(a) + static_cast<int32_t>(b);
return static_cast<INT>(sum < std::numeric_limits<INT>::min() ? std::numeric_limits<INT>::min() return static_cast<INT>(sum < std::numeric_limits<INT>::min() ? std::numeric_limits<INT>::min()
@@ -36,6 +58,13 @@ namespace isa {
: sum); : sum);
} }
/**
* @brief 饱和减法。
* @param a 被减数
* @param b 减数
* @return a-b,超出 INT 范围时夹到最小/最大值
* @details 中间量用 int32 计算,避免 int16 溢出未定义行为。
*/
inline INT sat_sub(INT a, INT b) { inline INT sat_sub(INT a, INT b) {
const int32_t diff = static_cast<int32_t>(a) - static_cast<int32_t>(b); const int32_t diff = static_cast<int32_t>(a) - static_cast<int32_t>(b);
return static_cast<INT>(diff < std::numeric_limits<INT>::min() ? std::numeric_limits<INT>::min() return static_cast<INT>(diff < std::numeric_limits<INT>::min() ? std::numeric_limits<INT>::min()
@@ -43,6 +72,13 @@ namespace isa {
: diff); : diff);
} }
/**
* @brief 饱和乘法。
* @param a 乘数
* @param b 乘数
* @return a*b,超出 INT 范围时夹到最小/最大值
* @details 中间量用 int32 计算,避免 int16 溢出未定义行为。
*/
inline INT sat_mul(INT a, INT b) { inline INT sat_mul(INT a, INT b) {
const int32_t prod = static_cast<int32_t>(a) * static_cast<int32_t>(b); const int32_t prod = static_cast<int32_t>(a) * static_cast<int32_t>(b);
return static_cast<INT>(prod < std::numeric_limits<INT>::min() ? std::numeric_limits<INT>::min() return static_cast<INT>(prod < std::numeric_limits<INT>::min() ? std::numeric_limits<INT>::min()
@@ -50,12 +86,17 @@ namespace isa {
: prod); : prod);
} }
/**
* @brief 饱和除法。
* @param a 被除数
* @param b 除数
* @return a/bb==0 视为除以 1 返回 aINT_MIN / -1 溢出饱和到 INT_MAX
* @details b==0 返回 a 是为避免未定义行为;除零的语义由 compiler/VM 层报错。
*/
inline INT sat_div(INT a, INT b) { inline INT sat_div(INT a, INT b) {
// b == 0 视为除以 1,避免未定义行为;除零的语义由 compiler/VM 层报错
if (b == 0) { if (b == 0) {
return a; return a;
} }
// INT_MIN / -1 溢出:饱和到 INT_MAX
if (a == std::numeric_limits<INT>::min() && b == -1) { if (a == std::numeric_limits<INT>::min() && b == -1) {
return std::numeric_limits<INT>::max(); return std::numeric_limits<INT>::max();
} }
+19 -1
View File
@@ -1,6 +1,6 @@
/** /**
* @file Encode.cpp * @file Encode.cpp
* @brief 指令编解码与反汇编 * @brief 指令编解码与反汇编实现
* @author * @author
* @date 2026-08-19 * @date 2026-08-19
*/ */
@@ -11,10 +11,20 @@
namespace isa { namespace isa {
/**
* @brief 编码:字段视图打包成一条 32 位指令字。
* @param d 解码后的字段视图
* @return 打包后的指令字;满足 encode(decode(w)) == w
*/
Instr encode(Decoded d) { Instr encode(Decoded d) {
return pack(d.op, d.rd, d.a, d.b); return pack(d.op, d.rd, d.a, d.b);
} }
/**
* @brief 解码:指令字拆成字段视图。
* @param w 32 位指令字
* @return 各字段视图
*/
Decoded decode(Instr w) { Decoded decode(Instr w) {
Decoded d; Decoded d;
d.op = op(w); d.op = op(w);
@@ -24,6 +34,14 @@ Decoded decode(Instr w) {
return d; return d;
} }
/**
* @brief 反汇编一条指令为一行文本。
* @param w 指令字
* @param out 输出缓冲
* @param cap 缓冲容量(含 '\0');cap==0 时直接返回、不写 out
* @details 按操作数形态表驱动输出,文本与 Doc/isa/指令与映像.md 一致;
* 未知操作码输出 `??? 0x<w>`。
*/
void disasm(Instr w, char* out, size_t cap) { void disasm(Instr w, char* out, size_t cap) {
if (cap == 0) { if (cap == 0) {
return; return;
+95 -35
View File
@@ -5,7 +5,7 @@
* @date 2026-08-21 * @date 2026-08-21
* *
* @details 格式契约见 Doc/isa/指令与映像.md12.13 修订:头 104 = 72 + 型号标识[32] * @details 格式契约见 Doc/isa/指令与映像.md12.13 修订:头 104 = 72 + 型号标识[32]
* 文件尾 SHA-256[32])。步骤 7:解析头与段;步骤 8补型号匹配与 SHA-256 校验。 * 文件尾 SHA-256[32])。解析头与段、补型号匹配与 SHA-256 校验都在本模块完成
*/ */
#pragma once #pragma once
@@ -17,71 +17,131 @@
namespace vm { namespace vm {
// 执行器内建支持型号(与 machine.toml [meta] 对齐;.stb 型号不匹配直接拒绝) /// 执行器内建支持型号(与 machine.toml [meta] 对齐;.stb 型号不匹配直接拒绝)
static const char* const kModelName = "STATOR"; static const char* const kModelName = "STATOR";
/// 执行器内建支持型号版本(与 machine.toml [meta] 对齐)。
static const uint32_t kModelVersion = 1; static const uint32_t kModelVersion = 1;
// 映像头(字段与 Doc/isa/指令与映像.md 一致) /**
* @brief 映像头字段(104 字节;字段顺序与 Doc/isa/指令与映像.md 一致)。
* @details 全部为小端值;型号标识 32 字节 @72 不在此结构内(见 model_id())。
*/
struct ImageHeader { struct ImageHeader {
uint32_t cycle_limit = 0; uint32_t cycle_limit = 0; ///< 每周期指令数上限(超出 → Fault::CycleLimit
uint32_t dt_ms = 0; uint32_t dt_ms = 0; ///< 周期时长(毫秒,定时器/计数器推进步长)
uint64_t project_hash = 0; uint64_t project_hash = 0; ///< 工程哈希(FNV-1a 64,只读展示)
uint32_t entry_fn_id = 0; uint32_t entry_fn_id = 0; ///< 入口函数(PROGRAM MAIN)在函数表的下标
uint32_t n_globals = 0; uint32_t n_globals = 0; ///< 全局变量槽数(数据段最前段)
uint32_t n_i = 0; uint32_t n_i = 0; ///< 输入变量(I)槽数
uint32_t n_q = 0; uint32_t n_q = 0; ///< 输出变量(Q)槽数
uint32_t n_m = 0; uint32_t n_m = 0; ///< 中间变量(M)槽数
uint32_t n_consts = 0; uint32_t n_consts = 0; ///< 常量表条目数
uint32_t n_funcs = 0; uint32_t n_funcs = 0; ///< 函数表行数
uint32_t offset_const = 0; uint32_t offset_const = 0; ///< 常量表段起点(相对文件头)
uint32_t offset_funcs = 0; uint32_t offset_funcs = 0; ///< 函数表段起点
uint32_t offset_code = 0; uint32_t offset_code = 0; ///< 字节码段起点
uint32_t offset_fb = 0; uint32_t offset_fb = 0; ///< FB 表段起点
uint32_t offset_data = 0; uint32_t offset_data = 0; ///< 数据段起点(之后为 SHA-256 文件尾)
}; };
/**
* @brief 函数表一行(12 字节)。
*/
struct FuncRow { struct FuncRow {
uint32_t nregs = 0; uint32_t nregs = 0; ///< 本函数寄存器数(函数头 nregs)
uint32_t code_offset = 0; // 相对字节码段起点(字节) uint32_t code_offset = 0; ///< 相对字节码段起点(字节)
uint32_t code_len = 0; // 指令条数 uint32_t code_len = 0; ///< 指令条数
}; };
/**
* @brief 常量表一项(12 字节)。
*/
struct ConstEntry { struct ConstEntry {
uint32_t tag = 0; uint32_t tag = 0; ///< 类型标记(isa::types::TypeTag0=BOOL、1=INT、2=TIME
uint64_t value = 0; uint64_t value = 0; ///< 值(LOADK 时按 tag 解释)
}; };
// 只读视图:校验过的映像(指向外部缓冲) /**
* @brief 只读视图:指向外部缓冲的校验过的 .stb 映像。
* @details from() 完成魔数/版本/头/各段/尺寸一致性校验;型号匹配与 SHA-256
* 由 model_matches() / sha_ok() 另行查询(Machine::create 里一起做)。
* 所有方法在校验失败(ok() == false)时返回安全默认值。
*/
class Image { class Image {
public: public:
/**
* @brief 从原始字节构造只读视图(不拷贝,调用方保证生命周期)。
* @param buf 映像缓冲;可为 nullptr
* @param len 缓冲字节数
* @return 校验结果;ok() 判成功,error() 取失败原因
* @details 校验项:非空、长度 ≥ 头、魔数 STSC、版本 1、五个段偏移单调且在
* SHA-256 尾之前、常量表/函数表尺寸一致、代码段 4 字节对齐、
* 入口 fn_id 在函数表内。
*/
static Image from(const uint8_t* buf, size_t len); static Image from(const uint8_t* buf, size_t len);
/**
* @brief 从 vector 构造只读视图。
* @param buf 映像缓冲(引用 data(),调用方保证生命周期)
* @return 同 from(const uint8_t*, size_t)
*/
static Image from(const std::vector<uint8_t>& buf); static Image from(const std::vector<uint8_t>& buf);
/// @return 校验是否通过。
bool ok() const { return ok_; } bool ok() const { return ok_; }
/// @return 校验失败原因;成功时为空串。
const std::string& error() const { return err_; } const std::string& error() const { return err_; }
/// @return 映像头字段。
const ImageHeader& header() const { return hdr_; } const ImageHeader& header() const { return hdr_; }
/**
* @brief 读函数表一行。
* @param i 函数下标
* @return 该行字段;越界(或校验失败)时全 0
*/
FuncRow func_row(size_t i) const; FuncRow func_row(size_t i) const;
/**
* @brief 读常量表一项。
* @param i 常量下标
* @return 该条目;越界(或校验失败)时全 0
*/
ConstEntry const_entry(size_t i) const; ConstEntry const_entry(size_t i) const;
const uint8_t* code_bytes() const; // 字节码段起点 /// @return 字节码段起点;校验失败返回 nullptr。
const uint8_t* data_bytes() const; // 数据段起点 const uint8_t* code_bytes() const;
size_t data_len() const; // 字节数(不含 SHA 尾)
// 12.13:型号标识与 SHA-256 校验 /// @return 数据段起点;校验失败返回 nullptr。
const uint8_t* data_bytes() const;
/// @return 数据段字节数(不含 SHA-256 尾);校验失败返回 0。
size_t data_len() const;
/// @return 型号标识字符串(头 @72 的 32 字节,去 '\0' 截断)。
std::string model_id() const; std::string model_id() const;
/**
* @brief 型号标识是否匹配。
* @param name 期望型号名(如 "STATOR"
* @param version 期望版本(如 1
* @return 头内 32 字节与 "name + version" 补零后逐字节相等
*/
bool model_matches(const std::string& name, uint32_t version) const; bool model_matches(const std::string& name, uint32_t version) const;
bool sha_ok() const; // 文件尾 32 字节 SHA-256 校验
/// @return 文件尾 32 字节是否为内容(去尾后)的 SHA-256。
bool sha_ok() const;
public: public:
// 默认构造为无效态(ok() == false /// 默认构造为无效态(ok() == false
Image() : buf_(nullptr), len_(0) {} Image() : buf_(nullptr), len_(0) {}
private: private:
const uint8_t* buf_; const uint8_t* buf_; ///< 外部缓冲指针(不持有)
size_t len_; size_t len_; ///< 缓冲长度
bool ok_ = false; bool ok_ = false; ///< 校验是否通过
std::string err_; std::string err_; ///< 失败原因
ImageHeader hdr_; ImageHeader hdr_; ///< 解析出的头字段
}; };
} }
+70 -41
View File
@@ -5,7 +5,8 @@
* @date 2026-08-21 * @date 2026-08-21
* *
* @details 设计说明(详见 Doc/vm/扫描周期.md 与 Doc/vm/指令执行.md): * @details 设计说明(详见 Doc/vm/扫描周期.md 与 Doc/vm/指令执行.md):
* - 只认 isa 映像(ImageView);无 GC、无堆、无线程 * - 只认 .stb 映像(vm 自带读实现;Machine::create 做型号/SHA-256 校验);
* 无 GC、无堆、无线程
* - 扫描周期:MAIN pc=0 → RET;MAIN 帧跨周期保留,调用栈深度上限 64 * - 扫描周期:MAIN pc=0 → RET;MAIN 帧跨周期保留,调用栈深度上限 64
* - 帧:{ fn_id, regs[nregs], ret_pc, ret_fn_id }CALL 压帧复制 r0..r7 * - 帧:{ fn_id, regs[nregs], ret_pc, ret_fn_id }CALL 压帧复制 r0..r7
* RET 复制回调用方(r0=结果) * RET 复制回调用方(r0=结果)
@@ -24,30 +25,41 @@
namespace vm { namespace vm {
// 周期/指令故障 /**
* @brief 周期/指令故障码。
*/
enum class Fault { enum class Fault {
None, // 正常 None, ///< 正常
CycleLimit, // 本周期指令数超过映像头 cycle_limit(用例 6 CycleLimit, ///< 本周期指令数超过映像头 cycle_limit(用例 6
StackOverflow, // 调用栈深度超过 64 StackOverflow, ///< 调用栈深度超过 64
BadOp, // 非法操作码op ≥ 29 BadOp, ///< 非法操作码 / 寄存器越界 / CALL 目标越出函数表
BadSlot, // slot × 8 + 8 越出数据区 BadSlot, ///< slot × 8 + 8 越出数据区
BadConst, // const_id 越出常量表 BadConst, ///< const_id 越出常量表
}; };
/**
* @brief 寄存器虚拟机:按扫描周期执行 .stb 映像。
* @details 一个实例 = 一台机器:持有映像只读视图 + 数据区工作副本 + 调用栈。
* MAIN 帧跨周期保留(PROGRAM 变量状态持久);每周期从 pc=0 执行到
* MAIN 的 RET,期间调用栈可进可出(上限 64 帧)。
* I 采样写入 / Q 读回由外部(executor)经 data() 完成,VM 只管数据区。
*/
class Machine { class Machine {
public: public:
/** /**
* @brief 从映像字节构建机器(校验 + 拷贝数据段 + 建 MAIN 帧) * @brief 从映像字节构建机器(校验 + 拷贝数据段 + 建 MAIN 帧)
* @param image .stb 映像字节 * @param image .stb 映像字节
* @param out 输出 Machine(未初始化) * @param out 输出 Machine(未初始化)
* @param err 错误输出;可为 nullptr(静默) * @param err 错误输出;可为 nullptr(静默)
* @return true 成功;false(映像非法,err 已写) * @return true 成功;false(映像非法,err 已写)
* @details 校验顺序:解析 .stbImage::from)→ SHA-256 → 型号标识匹配
* (内建 kModelName + kModelVersion),任一不符直接拒绝。
*/ */
static bool create(const std::vector<uint8_t>& image, Machine* out, static bool create(const std::vector<uint8_t>& image, Machine* out,
std::string* err); std::string* err);
/** /**
* @brief 跑一个扫描周期:MAIN pc=0 执行到 RET * @brief 跑一个扫描周期:MAIN pc=0 执行到 RET
* @return 故障(None = 正常完成);调用栈清空但 MAIN 帧保留 * @return 故障(None = 正常完成);调用栈清空但 MAIN 帧保留
*/ */
Fault run_cycle(); Fault run_cycle();
@@ -55,76 +67,93 @@ namespace vm {
// ---- 可观察性(v1 预留,12.11 供单步/回放/TUI---- // ---- 可观察性(v1 预留,12.11 供单步/回放/TUI----
/** /**
* @brief 执行一条指令,停在指令边界 * @brief 执行一条指令,停在指令边界
* @return true 继续;false 周期结束(MAIN 的 RET)或发生故障 * @return true 继续;false 周期结束(MAIN 的 RET)或发生故障
*/ */
bool step(); bool step();
/** @brief 最近一次故障(step 返回 false 后查询) */ /// @brief 最近一次故障(step 返回 false 后查询)
Fault fault() const; Fault fault() const;
/** @brief 周期是否已结束(MAIN 的 RET 后为 true */ /// @brief 周期是否已结束(MAIN 的 RET 后为 true
bool ended() const; bool ended() const;
/** @brief 映像头(dt_ms / cycle_limit 等) */ /// @brief 映像头(dt_ms / cycle_limit 等)
const vm::ImageHeader& header() const; const vm::ImageHeader& header() const;
/** @brief 当前指令下标(相对当前函数字节码段) */ /// @brief 当前指令下标(相对当前函数字节码段)
uint32_t pc() const; uint32_t pc() const;
/** @brief 当前函数 fn_id */ /// @brief 当前函数 fn_id
uint32_t fn_id() const; uint32_t fn_id() const;
/** @brief 本周期已执行指令数 */ /// @brief 本周期已执行指令数
uint32_t cycle_count() const; uint32_t cycle_count() const;
/** @brief 调用栈深度(MAIN 帧 = 1 */ /// @brief 调用栈深度(MAIN 帧 = 1
uint32_t call_depth() const; uint32_t call_depth() const;
/** @brief 数据区(I 采样写入 / Q 读回由外部做;8 字节定宽槽) */ /// @brief 数据区(I 采样写入 / Q 读回由外部做;8 字节定宽槽)
uint8_t* data(); uint8_t* data();
const uint8_t* data() const; const uint8_t* data() const;
/** @brief 数据区字节数 */ /// @brief 数据区字节数
size_t data_len() const; size_t data_len() const;
/** @brief 当前帧寄存器值(i < nregs */ /// @brief 当前帧寄存器值(i < nregs
int64_t reg(uint8_t i) const; int64_t reg(uint8_t i) const;
/** @brief 当前帧寄存器数(函数头 nregs) */ /// @brief 当前帧寄存器数(函数头 nregs)
uint32_t nregs() const; uint32_t nregs() const;
/** @brief 当前指令(pc_ 处;单步/观察用 */ /// @brief 当前指令(pc_ 处;单步/观察用pc 越界时返回 RET 哨兵)。
isa::Instr cur_instr() const; isa::Instr cur_instr() const;
private: private:
/**
* @brief 调用帧。
*/
struct Frame { struct Frame {
uint32_t fn_id = 0; // 本帧函数 uint32_t fn_id = 0; ///< 本帧函数
std::vector<int64_t> regs; // 寄存器文件(大小 = 函数头 nregs) std::vector<int64_t> regs; ///< 寄存器文件(大小 = 函数头 nregs)
uint32_t ret_pc = 0; // CALL 的下一条(非 MAIN 帧有意义) uint32_t ret_pc = 0; ///< CALL 的下一条(非 MAIN 帧有意义)
uint32_t ret_fn_id = 0; // 返回目标函数 uint32_t ret_fn_id = 0; ///< 返回目标函数
}; };
vm::Image image_; // 映像只读视图(vm 自实现) vm::Image image_; ///< 映像只读视图(vm 自实现,指向外部缓冲
std::vector<uint8_t> data_; // 数据区工作副本(8 字节定宽槽) std::vector<uint8_t> data_; ///< 数据区工作副本(8 字节定宽槽)
std::vector<Frame> frames_; // 调用栈([0] = MAIN,跨周期保留) std::vector<Frame> frames_; ///< 调用栈([0] = MAIN,跨周期保留)
// 边沿检测上次输入(每槽 2 字节:[slot*2] 第一边沿、[slot*2+1] 第二边沿; /**
// CTU/CTD/R_TRIG/F_TRIG 用第一、CTUD 用两个),跨周期保留 * @brief 边沿检测上次输入(每槽 2 字节:[slot*2] 第一边沿、[slot*2+1] 第二边沿;
* CTU/CTD/R_TRIG/F_TRIG 用第一、CTUD 用两个),跨周期保留。
*/
std::vector<uint8_t> edge_prev_; std::vector<uint8_t> edge_prev_;
uint32_t pc_ = 0; // 当前 pc(相对本帧函数字节码段) uint32_t pc_ = 0; ///< 当前 pc(相对本帧函数字节码段)
uint32_t cycle_count_ = 0; // 本周期指令数 uint32_t cycle_count_ = 0; ///< 本周期指令数
Fault fault_ = Fault::None; // 最近一次故障 Fault fault_ = Fault::None;///< 最近一次故障
bool ended_ = false; // step 后周期是否已结束 bool ended_ = false; ///< step 后周期是否已结束
/// @brief 当前(栈顶)帧引用。
Frame& cur_frame(); Frame& cur_frame();
/// @brief 当前(栈顶)帧常量引用。
const Frame& cur_frame() const; const Frame& cur_frame() const;
bool exec_one(); // 译码执行一条(12.9 步骤 2/3/4 填充)
Fault do_call(uint32_t fn_id); // 压帧;BadFn 用 BadOp 表示
Fault do_ret(); // 弹帧 / 周期结束
Fault do_cal(uint8_t op, uint16_t slot); // TON/TOF/CTU12.9 步骤 4
// 数据区槽读写(8 字节定宽;越界返回 false) /// @brief 译码执行一条;false = 故障或周期结束。
bool exec_one();
/// @brief 压帧(复制 r0..r7);fn_id 越界以 BadOp 表示。
Fault do_call(uint32_t fn_id);
/// @brief 弹帧 / 周期结束(复制 r0..r7 回调用方)。
Fault do_ret();
/// @brief 执行内置 FBTON/TOF/TP/CTU/CTD/CTUD/R_TRIG/F_TRIG)。
Fault do_cal(uint8_t op, uint16_t slot);
/// @brief 读数据区槽(8 字节定宽;越界返回 false)。
bool slot_get(uint16_t slot, int64_t* out) const; bool slot_get(uint16_t slot, int64_t* out) const;
/// @brief 写数据区槽(8 字节定宽;越界返回 false)。
bool slot_set(uint16_t slot, int64_t v); bool slot_set(uint16_t slot, int64_t v);
}; };
} }
+93 -7
View File
@@ -1,6 +1,6 @@
/** /**
* @file Image.cpp * @file Image.cpp
* @brief vm 自带的 .stb 只读视图(执行器侧) * @brief vm 自带的 .stb 只读视图实现(执行器侧compiler 各有实现
* @author * @author
* @date 2026-08-21 * @date 2026-08-21
*/ */
@@ -14,14 +14,22 @@ namespace vm {
namespace { namespace {
const uint32_t kMagic = 0x43545353u; // "STSC" 小端 /// 映像魔数:"STSC" 小端
const uint32_t kMagic = 0x43545353u;
/// 映像格式版本。
const uint32_t kVersion = 1; const uint32_t kVersion = 1;
/// 映像头字节数(72 原字段 + 型号标识[32] @7212.13 修订)。
const size_t kHeaderSize = 104; const size_t kHeaderSize = 104;
/// 常量表一行字节数(tag:4 + value:8)。
const size_t kConstEntrySize = 12; const size_t kConstEntrySize = 12;
/// 函数表一行字节数(nregs/code_offset/code_len 各 4)。
const size_t kFuncRowSize = 12; const size_t kFuncRowSize = 12;
/// SHA-256 摘要长度(文件尾)。
const size_t kSha256Size = 32; const size_t kSha256Size = 32;
/// 型号标识长度(头内 @72,不足补 '\0')。
const size_t kModelIdSize = 32; const size_t kModelIdSize = 32;
/// 小端读 32 位。
uint32_t get_le32(const uint8_t* p) { uint32_t get_le32(const uint8_t* p) {
return static_cast<uint32_t>(p[0]) return static_cast<uint32_t>(p[0])
| (static_cast<uint32_t>(p[1]) << 8) | (static_cast<uint32_t>(p[1]) << 8)
@@ -29,6 +37,7 @@ namespace {
| (static_cast<uint32_t>(p[3]) << 24); | (static_cast<uint32_t>(p[3]) << 24);
} }
/// 小端读 64 位。
uint64_t get_le64(const uint8_t* p) { uint64_t get_le64(const uint8_t* p) {
uint64_t v = 0; uint64_t v = 0;
for (int i = 0; i < 8; ++i) { for (int i = 0; i < 8; ++i) {
@@ -39,6 +48,7 @@ namespace {
// ---- SHA-256(执行器侧实现,与 compiler 各一份)---- // ---- SHA-256(执行器侧实现,与 compiler 各一份)----
/// SHA-256 轮常量 K[0..63]。
const uint32_t kShaK[64] = { const uint32_t kShaK[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
@@ -53,15 +63,26 @@ namespace {
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
}; };
/// 循环右移。
inline uint32_t rotr(uint32_t x, uint32_t n) { return (x >> n) | (x << (32 - n)); } inline uint32_t rotr(uint32_t x, uint32_t n) { return (x >> n) | (x << (32 - n)); }
/**
* @brief SHA-256 增量状态机。
* @details 标准 FIPS 180-4 实现:update() 吸收任意长度字节流,final() 输出
* 32 字节大端摘要。按 64 字节块 process()。
*/
struct Sha256 { struct Sha256 {
uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; ///< 初始哈希值
uint64_t total = 0; uint64_t total = 0; ///< 已吸收字节数(final 时编码进长度域)
uint8_t block[64]; uint8_t block[64]; ///< 当前块缓冲
size_t block_len = 0; size_t block_len = 0; ///< 块缓冲已用字节数
/**
* @brief 吸收数据。
* @param data 输入字节
* @param len 字节数
*/
void update(const uint8_t* data, size_t len) { void update(const uint8_t* data, size_t len) {
total += len; total += len;
while (len > 0) { while (len > 0) {
@@ -83,6 +104,7 @@ namespace {
} }
} }
/// 压缩一个满块(64 字节,w[0..63] 展开 + 64 轮)。
void process() { void process() {
uint32_t w[64]; uint32_t w[64];
for (int i = 0; i < 16; ++i) { for (int i = 0; i < 16; ++i) {
@@ -115,6 +137,10 @@ namespace {
h[4] += e; h[5] += f; h[6] += g; h[7] += hh; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
} }
/**
* @brief 结束并输出摘要。
* @param out 32 字节输出缓冲(大端)
*/
void final(uint8_t out[32]) { void final(uint8_t out[32]) {
const uint64_t bitlen = total * 8; const uint64_t bitlen = total * 8;
const uint8_t pad = 0x80; const uint8_t pad = 0x80;
@@ -136,18 +162,31 @@ namespace {
} }
} }
/// 大端读 32 位。
static uint32_t get_be32(const uint8_t* p) { static uint32_t get_be32(const uint8_t* p) {
return (static_cast<uint32_t>(p[0]) << 24) | (static_cast<uint32_t>(p[1]) << 16) | return (static_cast<uint32_t>(p[0]) << 24) | (static_cast<uint32_t>(p[1]) << 16) |
(static_cast<uint32_t>(p[2]) << 8) | static_cast<uint32_t>(p[3]); (static_cast<uint32_t>(p[2]) << 8) | static_cast<uint32_t>(p[3]);
} }
}; };
/**
* @brief 一次性 SHA-256。
* @param data 输入字节
* @param len 字节数
* @param out 32 字节摘要输出
*/
void sha256(const uint8_t* data, size_t len, uint8_t out[32]) { void sha256(const uint8_t* data, size_t len, uint8_t out[32]) {
Sha256 s; Sha256 s;
s.update(data, len); s.update(data, len);
s.final(out); s.final(out);
} }
/**
* @brief 按型号标识约定填充 32 字节:name + version(如 "STATOR1"),余下补 '\0'。
* @param name 型号名
* @param version 版本号
* @param out 32 字节输出缓冲
*/
void fill_model_id(const std::string& name, uint32_t version, char out[32]) { void fill_model_id(const std::string& name, uint32_t version, char out[32]) {
const std::string id = name + std::to_string(version); const std::string id = name + std::to_string(version);
for (size_t i = 0; i < 32; ++i) { for (size_t i = 0; i < 32; ++i) {
@@ -157,6 +196,12 @@ namespace {
} // namespace } // namespace
/**
* @brief 从原始字节构造只读视图(不拷贝,调用方保证生命周期)。
* @param buf 映像缓冲;可为 nullptr
* @param len 缓冲字节数
* @return 校验结果;ok() 判成功,error() 取失败原因
*/
Image Image::from(const uint8_t* buf, size_t len) { Image Image::from(const uint8_t* buf, size_t len) {
Image v; Image v;
v.buf_ = buf; v.buf_ = buf;
@@ -194,7 +239,7 @@ Image Image::from(const uint8_t* buf, size_t len) {
h.offset_fb = get_le32(buf + 64); h.offset_fb = get_le32(buf + 64);
h.offset_data = get_le32(buf + 68); h.offset_data = get_le32(buf + 68);
// 段校验(数据段之后是 SHA-256 文件尾;步骤 8 做校验,这里仅保证有尾) // 段校验(数据段之后是 SHA-256 文件尾;这里仅保证有尾sha_ok() 做完整性校验
if (len < static_cast<size_t>(h.offset_data) + kSha256Size) { if (len < static_cast<size_t>(h.offset_data) + kSha256Size) {
v.err_ = "missing sha256 tail"; v.err_ = "missing sha256 tail";
return v; return v;
@@ -232,10 +277,20 @@ Image Image::from(const uint8_t* buf, size_t len) {
return v; return v;
} }
/**
* @brief 从 vector 构造只读视图。
* @param buf 映像缓冲(引用 data(),调用方保证生命周期)
* @return 同 from(const uint8_t*, size_t)
*/
Image Image::from(const std::vector<uint8_t>& buf) { Image Image::from(const std::vector<uint8_t>& buf) {
return from(buf.data(), buf.size()); return from(buf.data(), buf.size());
} }
/**
* @brief 读函数表一行。
* @param i 函数下标
* @return 该行字段;越界(或校验失败)时全 0
*/
FuncRow Image::func_row(size_t i) const { FuncRow Image::func_row(size_t i) const {
FuncRow r; FuncRow r;
if (ok_ && i < hdr_.n_funcs) { if (ok_ && i < hdr_.n_funcs) {
@@ -247,6 +302,11 @@ FuncRow Image::func_row(size_t i) const {
return r; return r;
} }
/**
* @brief 读常量表一项。
* @param i 常量下标
* @return 该条目;越界(或校验失败)时全 0
*/
ConstEntry Image::const_entry(size_t i) const { ConstEntry Image::const_entry(size_t i) const {
ConstEntry e; ConstEntry e;
if (ok_ && i < hdr_.n_consts) { if (ok_ && i < hdr_.n_consts) {
@@ -257,18 +317,34 @@ ConstEntry Image::const_entry(size_t i) const {
return e; return e;
} }
/**
* @brief 字节码段起点。
* @return 段指针;校验失败返回 nullptr
*/
const uint8_t* Image::code_bytes() const { const uint8_t* Image::code_bytes() const {
return ok_ ? buf_ + hdr_.offset_code : nullptr; return ok_ ? buf_ + hdr_.offset_code : nullptr;
} }
/**
* @brief 数据段起点。
* @return 段指针;校验失败返回 nullptr
*/
const uint8_t* Image::data_bytes() const { const uint8_t* Image::data_bytes() const {
return ok_ ? buf_ + hdr_.offset_data : nullptr; return ok_ ? buf_ + hdr_.offset_data : nullptr;
} }
/**
* @brief 数据段字节数。
* @return 段长度(不含 SHA-256 尾);校验失败返回 0
*/
size_t Image::data_len() const { size_t Image::data_len() const {
return ok_ ? (len_ - kSha256Size) - hdr_.offset_data : 0; return ok_ ? (len_ - kSha256Size) - hdr_.offset_data : 0;
} }
/**
* @brief 型号标识字符串。
* @return 头 @72 起 32 字节,去 '\0' 截断;校验失败返回空串
*/
std::string Image::model_id() const { std::string Image::model_id() const {
if (!ok_) { if (!ok_) {
return ""; return "";
@@ -281,12 +357,22 @@ std::string Image::model_id() const {
return s; return s;
} }
/**
* @brief 型号标识是否匹配。
* @param name 期望型号名(如 "STATOR"
* @param version 期望版本(如 1
* @return 头内 32 字节与 "name + version" 补零后逐字节相等
*/
bool Image::model_matches(const std::string& name, uint32_t version) const { bool Image::model_matches(const std::string& name, uint32_t version) const {
char want[kModelIdSize]; char want[kModelIdSize];
fill_model_id(name, version, want); fill_model_id(name, version, want);
return std::memcmp(buf_ + 72, want, kModelIdSize) == 0; return std::memcmp(buf_ + 72, want, kModelIdSize) == 0;
} }
/**
* @brief 文件尾 SHA-256 完整性校验。
* @return 对 len-32 字节内容算摘要,与文件尾 32 字节相等
*/
bool Image::sha_ok() const { bool Image::sha_ok() const {
if (!ok_) { if (!ok_) {
return false; return false;
+83 -5
View File
@@ -1,15 +1,13 @@
/** /**
* @file Machine.cpp * @file Machine.cpp
* @brief 寄存器虚拟机(12.9,步骤 2:译码 switch * @brief 寄存器虚拟机实现12.9:译码 switch + CALL/RET 帧栈 + CAL_* 定时器
* @author * @author
* @date 2026-08-21 * @date 2026-08-21
* *
* @details 设计说明(详见 Doc/vm/指令执行.md): * @details 设计说明(详见 Doc/vm/指令执行.md):
* - 步骤 2 范围:create / run_cycle / step + 标量指令(MOVE/LOADK/NOT/AND/OR/算术/CMP)、
* 跳转(JMP/JT/JF)、LOAD/STOREslot × 8);RET 仅处理 MAIN(周期结束)
* - 步骤 3 补 CALL/RET 帧栈与栈深/坏操作码故障;步骤 4 补 CAL_* 定时器
* - 取指:函数表 → code_offset(字节)→ u32;执行后 pc 先 +1,跳转再 pc += off * - 取指:函数表 → code_offset(字节)→ u32;执行后 pc 先 +1,跳转再 pc += off
* - 数据区 8 字节定宽槽:偏移 = slot × 8 * - 数据区 8 字节定宽槽:偏移 = slot × 8
* - 寄存器越界检查仅对把字段当寄存器的指令;a|b 作偏移/槽号/常量 id 时跳过
*/ */
#include "vm/Machine.h" #include "vm/Machine.h"
@@ -23,6 +21,16 @@
namespace vm { namespace vm {
/**
* @brief 从映像字节构建机器(校验 + 拷贝数据段 + 建 MAIN 帧)。
* @param image .stb 映像字节
* @param out 输出 Machine(未初始化)
* @param err 错误输出;可为 nullptr(静默)
* @return true 成功;false(映像非法,err 已写)
* @details 校验顺序:解析 .stbImage::from)→ SHA-256 → 型号标识匹配;
* 通过后拷贝数据段为工作副本,初始化边沿检测缓冲(每槽 2 字节),
* 建 MAIN 帧(跨周期保留)并把执行状态复位。
*/
bool Machine::create(const std::vector<uint8_t>& image, Machine* out, bool Machine::create(const std::vector<uint8_t>& image, Machine* out,
std::string* err) { std::string* err) {
out->image_ = vm::Image::from(image); out->image_ = vm::Image::from(image);
@@ -67,6 +75,12 @@ bool Machine::create(const std::vector<uint8_t>& image, Machine* out,
return true; return true;
} }
/**
* @brief 跑一个扫描周期:MAIN pc=0 执行到 RET。
* @return 故障(None = 正常完成)
* @details 循环执行 exec_one() 直到周期结束或故障;结束/故障后清空调用栈
* (保留 MAIN 帧,PROGRAM 变量状态跨周期持久)。
*/
Fault Machine::run_cycle() { Fault Machine::run_cycle() {
cycle_count_ = 0; cycle_count_ = 0;
ended_ = false; ended_ = false;
@@ -84,6 +98,10 @@ Fault Machine::run_cycle() {
return fault_; return fault_;
} }
/**
* @brief 执行一条指令,停在指令边界。
* @return true 继续;false 周期结束(MAIN 的 RET)或发生故障
*/
bool Machine::step() { bool Machine::step() {
if (ended_ || fault_ != Fault::None) { if (ended_ || fault_ != Fault::None) {
return false; return false;
@@ -103,10 +121,19 @@ const uint8_t* Machine::data() const { return data_.data(); }
size_t Machine::data_len() const { return data_.size(); } size_t Machine::data_len() const { return data_.size(); }
int64_t Machine::reg(uint8_t i) const { return cur_frame().regs[i]; } int64_t Machine::reg(uint8_t i) const { return cur_frame().regs[i]; }
/**
* @brief 当前帧寄存器数。
* @return 栈顶帧 regs 大小(函数头 nregs
*/
uint32_t Machine::nregs() const { uint32_t Machine::nregs() const {
return static_cast<uint32_t>(cur_frame().regs.size()); return static_cast<uint32_t>(cur_frame().regs.size());
} }
/**
* @brief 当前指令(pc_ 处)。
* @return 指令字;pc_ 越出本函数字节码段时返回 RET 哨兵
* @details 供单步/观察用;不修改任何执行状态。
*/
isa::Instr Machine::cur_instr() const { isa::Instr Machine::cur_instr() const {
const vm::FuncRow row = image_.func_row(cur_frame().fn_id); const vm::FuncRow row = image_.func_row(cur_frame().fn_id);
const uint8_t* base = image_.code_bytes() + row.code_offset; const uint8_t* base = image_.code_bytes() + row.code_offset;
@@ -116,9 +143,20 @@ isa::Instr Machine::cur_instr() const {
return reinterpret_cast<const uint32_t*>(base)[pc_]; return reinterpret_cast<const uint32_t*>(base)[pc_];
} }
/// @brief 当前(栈顶)帧引用。
Machine::Frame& Machine::cur_frame() { return frames_.back(); } Machine::Frame& Machine::cur_frame() { return frames_.back(); }
/// @brief 当前(栈顶)帧常量引用。
const Machine::Frame& Machine::cur_frame() const { return frames_.back(); } const Machine::Frame& Machine::cur_frame() const { return frames_.back(); }
/**
* @brief 译码执行一条指令。
* @return true 继续;false 故障(fault_ 已置)或周期结束
* @details 流程:取指(越界 → BadOp)→ 周期计数(超 cycle_limit → CycleLimit)→
* pc 先 +1(跳转按"相对下一条"叠加)→ 寄存器越界检查 → 按操作码分发。
* 标量指令用 isa::types 饱和算术;LOAD/STORE 走 slot_get/slot_set
* CALL/RET 走 do_call/do_retCAL_* 走 do_cal。
*/
bool Machine::exec_one() { bool Machine::exec_one() {
// ---- 取指 ---- // ---- 取指 ----
const vm::FuncRow row = image_.func_row(cur_frame().fn_id); const vm::FuncRow row = image_.func_row(cur_frame().fn_id);
@@ -180,10 +218,11 @@ bool Machine::exec_one() {
return false; return false;
} }
const vm::ConstEntry c = image_.const_entry(cid); const vm::ConstEntry c = image_.const_entry(cid);
// 按类型标记解释常量值:BOOL 归一化 0/1,INT 符号扩展,TIME 全 64 位
if (c.tag == isa::types::Bool) { if (c.tag == isa::types::Bool) {
regs[rd] = c.value ? 1 : 0; regs[rd] = c.value ? 1 : 0;
} else if (c.tag == isa::types::Int) { } else if (c.tag == isa::types::Int) {
regs[rd] = static_cast<int16_t>(c.value); // 符号扩展 regs[rd] = static_cast<int16_t>(c.value);
} else { } else {
regs[rd] = static_cast<int64_t>(c.value); regs[rd] = static_cast<int64_t>(c.value);
} }
@@ -293,6 +332,12 @@ bool Machine::exec_one() {
} }
} }
/**
* @brief 读数据区槽(8 字节定宽,小端)。
* @param slot 槽号
* @param out 输出值
* @return false = slot × 8 + 8 越出数据区
*/
bool Machine::slot_get(uint16_t slot, int64_t* out) const { bool Machine::slot_get(uint16_t slot, int64_t* out) const {
const size_t off = static_cast<size_t>(slot) * 8; const size_t off = static_cast<size_t>(slot) * 8;
if (off + 8 > data_.size()) { if (off + 8 > data_.size()) {
@@ -306,6 +351,12 @@ bool Machine::slot_get(uint16_t slot, int64_t* out) const {
return true; return true;
} }
/**
* @brief 写数据区槽(8 字节定宽,小端)。
* @param slot 槽号
* @param v 要写入的值
* @return false = slot × 8 + 8 越出数据区
*/
bool Machine::slot_set(uint16_t slot, int64_t v) { bool Machine::slot_set(uint16_t slot, int64_t v) {
const size_t off = static_cast<size_t>(slot) * 8; const size_t off = static_cast<size_t>(slot) * 8;
if (off + 8 > data_.size()) { if (off + 8 > data_.size()) {
@@ -317,6 +368,14 @@ bool Machine::slot_set(uint16_t slot, int64_t v) {
return true; return true;
} }
/**
* @brief 调用:压新帧。
* @param fn_id 目标函数(函数表下标)
* @return Faultfn_id 越界 → BadOp;栈深 ≥ 64 → StackOverflow;成功 → None
* @details 新帧寄存器清零,ret_pc = 当前 pc(已指向 CALL 下一条);
* 按调用约定把调用方 r0..r7 复制进新帧(实参已由调用点 MOVE 进 r1..r7);
* pc 复位到新函数起点。
*/
Fault Machine::do_call(uint32_t fn_id) { Fault Machine::do_call(uint32_t fn_id) {
if (fn_id >= image_.header().n_funcs) { if (fn_id >= image_.header().n_funcs) {
return Fault::BadOp; return Fault::BadOp;
@@ -340,6 +399,13 @@ Fault Machine::do_call(uint32_t fn_id) {
return Fault::None; return Fault::None;
} }
/**
* @brief 返回:弹帧 / 周期结束。
* @return Fault(成功 → None
* @details MAIN 帧的 RETended_ = true(周期结束,不弹帧)。
* 非 MAIN 帧:按调用约定把 r0..r7 复制回调用方(r0 = 结果,r1..r7 原样),
* pc 恢复为 ret_pc,弹帧。
*/
Fault Machine::do_ret() { Fault Machine::do_ret() {
if (frames_.size() <= 1) { if (frames_.size() <= 1) {
ended_ = true; // MAIN 的 RET:周期结束 ended_ = true; // MAIN 的 RET:周期结束
@@ -357,6 +423,18 @@ Fault Machine::do_ret() {
return Fault::None; return Fault::None;
} }
/**
* @brief 执行内置 FBCAL_*)。
* @param op 操作码(CAL_TON..CAL_F_TRIG8 个)
* @param slot 实例起始槽号
* @return Fault(槽越界 → BadSlot;非 CAL_* → BadOp;成功 → None
* @details 内建 FB 布局冻结(Doc/compiler/符号表与链接.md):
* - TON/TOF/TPin/pt/q/et(字段 0/1/2/3
* - CTUcu/r/pv/q/cv0/1/2/3/4);CTDcd/ld/pv/q/cv(同)
* - CTUDcu/cd/r/lu/pv/qu/qd/cv0..7
* - R_TRIG / F_TRIGclk/q0/1
* 字段偏移 = 字段序号 × 8(8 字节定宽槽);边沿存 edge_prev_(每槽 2 字节)。
*/
Fault Machine::do_cal(uint8_t op, uint16_t slot) { Fault Machine::do_cal(uint8_t op, uint16_t slot) {
// 内建 FB 布局冻结(Doc/compiler/符号表与链接.md): // 内建 FB 布局冻结(Doc/compiler/符号表与链接.md):
// TON/TOF/TPin/pt/q/et(字段 0/1/2/3 // TON/TOF/TPin/pt/q/et(字段 0/1/2/3