codecin 7.22.10__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codecin/__init__.py +27 -0
- codecin/aot.py +1057 -0
- codecin/assembler.py +619 -0
- codecin/cbackend.py +3024 -0
- codecin/cin.py +4265 -0
- codecin/cli.py +670 -0
- codecin/codecin_native.dll +0 -0
- codecin/config.py +50 -0
- codecin/console.py +183 -0
- codecin/cpu.py +312 -0
- codecin/crom.py +449 -0
- codecin/cvm.py +708 -0
- codecin/disasm.py +149 -0
- codecin/environment.py +176 -0
- codecin/errors.py +54 -0
- codecin/isa.py +560 -0
- codecin/lib/array/pic.toml +10 -0
- codecin/lib/array/src/array.cin +103 -0
- codecin/lib/bigint/pic.toml +10 -0
- codecin/lib/bigint/src/bigint.cin +589 -0
- codecin/lib/bits/pic.toml +10 -0
- codecin/lib/bits/src/bits.cin +143 -0
- codecin/lib/bitset/pic.toml +10 -0
- codecin/lib/bitset/src/bitset.cin +374 -0
- codecin/lib/codec/pic.toml +10 -0
- codecin/lib/codec/src/codec.cin +563 -0
- codecin/lib/combin/pic.toml +10 -0
- codecin/lib/combin/src/combin.cin +414 -0
- codecin/lib/conv/pic.toml +10 -0
- codecin/lib/conv/src/conv.cin +151 -0
- codecin/lib/cppstd/pic.toml +10 -0
- codecin/lib/cppstd/src/cppstd.cin +418 -0
- codecin/lib/cstd/pic.toml +10 -0
- codecin/lib/cstd/src/cstd.cin +424 -0
- codecin/lib/csv/pic.toml +10 -0
- codecin/lib/csv/src/csv.cin +405 -0
- codecin/lib/dp/pic.toml +10 -0
- codecin/lib/dp/src/dp.cin +325 -0
- codecin/lib/ffi/pic.toml +10 -0
- codecin/lib/ffi/src/ffi.cin +163 -0
- codecin/lib/fmt/pic.toml +10 -0
- codecin/lib/fmt/src/fmt.cin +325 -0
- codecin/lib/frac/pic.toml +10 -0
- codecin/lib/frac/src/frac.cin +252 -0
- codecin/lib/gostd/pic.toml +10 -0
- codecin/lib/gostd/src/gostd.cin +415 -0
- codecin/lib/graph/pic.toml +10 -0
- codecin/lib/graph/src/graph.cin +367 -0
- codecin/lib/gui/pic.toml +10 -0
- codecin/lib/gui/src/gui.cin +218 -0
- codecin/lib/hash/pic.toml +10 -0
- codecin/lib/hash/src/hash.cin +67 -0
- codecin/lib/heap/pic.toml +10 -0
- codecin/lib/heap/src/heap.cin +199 -0
- codecin/lib/io/pic.toml +10 -0
- codecin/lib/io/src/io.cin +141 -0
- codecin/lib/json/pic.toml +10 -0
- codecin/lib/json/src/json.cin +84 -0
- codecin/lib/key/pic.toml +10 -0
- codecin/lib/key/src/key.cin +78 -0
- codecin/lib/math/pic.toml +10 -0
- codecin/lib/math/src/math.cin +50 -0
- codecin/lib/matrix/pic.toml +10 -0
- codecin/lib/matrix/src/matrix.cin +155 -0
- codecin/lib/net/pic.toml +10 -0
- codecin/lib/net/src/net.cin +171 -0
- codecin/lib/path/pic.toml +10 -0
- codecin/lib/path/src/path.cin +372 -0
- codecin/lib/queue/pic.toml +10 -0
- codecin/lib/queue/src/queue.cin +112 -0
- codecin/lib/rand/pic.toml +10 -0
- codecin/lib/rand/src/rand.cin +46 -0
- codecin/lib/set/pic.toml +10 -0
- codecin/lib/set/src/set.cin +269 -0
- codecin/lib/sort/pic.toml +10 -0
- codecin/lib/sort/src/sort.cin +93 -0
- codecin/lib/stat/pic.toml +10 -0
- codecin/lib/stat/src/stat.cin +138 -0
- codecin/lib/str/pic.toml +10 -0
- codecin/lib/str/src/str.cin +54 -0
- codecin/lib/termux/pic.toml +10 -0
- codecin/lib/termux/src/termux.cin +118 -0
- codecin/lib/test/pic.toml +10 -0
- codecin/lib/test/src/test.cin +74 -0
- codecin/lib/text/pic.toml +10 -0
- codecin/lib/text/src/text.cin +323 -0
- codecin/lib/time/pic.toml +10 -0
- codecin/lib/time/src/time.cin +54 -0
- codecin/lib/token/pic.toml +10 -0
- codecin/lib/token/src/token.cin +183 -0
- codecin/lib/tree/pic.toml +10 -0
- codecin/lib/tree/src/tree.cin +256 -0
- codecin/lib/unionfind/pic.toml +10 -0
- codecin/lib/unionfind/src/unionfind.cin +115 -0
- codecin/lib/validate/pic.toml +10 -0
- codecin/lib/validate/src/validate.cin +148 -0
- codecin/lib/vec/pic.toml +10 -0
- codecin/lib/vec/src/vec.cin +88 -0
- codecin/logger.py +145 -0
- codecin/memory.py +306 -0
- codecin/mkn.py +916 -0
- codecin/native/aot/aot.go +114 -0
- codecin/native/aot/stub_main.go.txt +23 -0
- codecin/native/build.ps1 +33 -0
- codecin/native/build.sh +48 -0
- codecin/native/cmd/cincc/main.go +66 -0
- codecin/native/compiler/codegen.go +2238 -0
- codecin/native/compiler/compile_test.go +1069 -0
- codecin/native/compiler/parser.go +1331 -0
- codecin/native/compiler/syscalls.go +166 -0
- codecin/native/compiler/tokenizer.go +394 -0
- codecin/native/compiler/types.go +217 -0
- codecin/native/engine/args.go +37 -0
- codecin/native/engine/audio.go +402 -0
- codecin/native/engine/audio_other.go +105 -0
- codecin/native/engine/audio_test.go +279 -0
- codecin/native/engine/audio_windows.go +190 -0
- codecin/native/engine/canvas.go +271 -0
- codecin/native/engine/console_other.go +9 -0
- codecin/native/engine/console_windows.go +43 -0
- codecin/native/engine/crom.go +86 -0
- codecin/native/engine/encode.go +93 -0
- codecin/native/engine/engine_test.go +198 -0
- codecin/native/engine/ffi_nocgo.go +20 -0
- codecin/native/engine/ffi_registry.go +69 -0
- codecin/native/engine/ffi_unix.go +109 -0
- codecin/native/engine/ffi_windows.go +117 -0
- codecin/native/engine/gui.go +209 -0
- codecin/native/engine/gui_stub.go +13 -0
- codecin/native/engine/gui_test.go +148 -0
- codecin/native/engine/gui_windows.go +604 -0
- codecin/native/engine/gui_x11.go +723 -0
- codecin/native/engine/host_test.go +139 -0
- codecin/native/engine/hostcrypto.go +30 -0
- codecin/native/engine/hostdesktop.go +173 -0
- codecin/native/engine/hostnet.go +127 -0
- codecin/native/engine/isa_gen.go +689 -0
- codecin/native/engine/keyboard.go +432 -0
- codecin/native/engine/keyboard_other.go +94 -0
- codecin/native/engine/keyboard_stub.go +17 -0
- codecin/native/engine/keyboard_termios_darwin.go +9 -0
- codecin/native/engine/keyboard_termios_linux.go +9 -0
- codecin/native/engine/keyboard_test.go +246 -0
- codecin/native/engine/keyboard_windows.go +208 -0
- codecin/native/engine/keyboard_windows_test.go +123 -0
- codecin/native/engine/lineedit.go +262 -0
- codecin/native/engine/lineedit_test.go +105 -0
- codecin/native/engine/lineint_unix.go +17 -0
- codecin/native/engine/lineint_windows.go +19 -0
- codecin/native/engine/mem_other.go +37 -0
- codecin/native/engine/mem_windows.go +33 -0
- codecin/native/engine/native.go +640 -0
- codecin/native/engine/netsock.go +321 -0
- codecin/native/engine/ops_ext.go +515 -0
- codecin/native/engine/stdin.go +72 -0
- codecin/native/engine/stdin_other.go +9 -0
- codecin/native/engine/stdin_windows.go +60 -0
- codecin/native/engine/system.go +313 -0
- codecin/native/engine/termux.go +180 -0
- codecin/native/engine/version_gen.go +7 -0
- codecin/native/engine/vkb_darwin.go +62 -0
- codecin/native/engine/vkb_linux.go +95 -0
- codecin/native/engine/vkb_stub.go +11 -0
- codecin/native/engine/vm.go +1677 -0
- codecin/native/go.mod +3 -0
- codecin/native/ir/ir.go +48 -0
- codecin/native/main.go +448 -0
- codecin/native/mc/aarch64.go +165 -0
- codecin/native/mc/aarch64_test.go +30 -0
- codecin/native/mc/elf.go +88 -0
- codecin/native/mc/print_test.go +52 -0
- codecin/native/mc/x86_64.go +1262 -0
- codecin/native/mc/x86_64_test.go +102 -0
- codecin/native.py +432 -0
- codecin/native_codegen.py +987 -0
- codecin/nativegen.py +786 -0
- codecin/object.py +539 -0
- codecin/optimizer.py +236 -0
- codecin/packaging/__init__.py +46 -0
- codecin/packaging/archive.py +177 -0
- codecin/packaging/model.py +519 -0
- codecin/packaging/spec.py +193 -0
- codecin/packaging/store.py +372 -0
- codecin/packaging/toml.py +541 -0
- codecin/packaging/vcs.py +215 -0
- codecin/pic.py +1917 -0
- codecin/pic_api.py +374 -0
- codecin/pic_login.py +519 -0
- codecin/pic_registry.py +515 -0
- codecin/registers.py +130 -0
- codecin/sdgcc.py +493 -0
- codecin/stats.py +230 -0
- codecin/stdlib.py +138 -0
- codecin/toolchain.py +396 -0
- codecin/toolkit.py +26 -0
- codecin/version.py +260 -0
- codecin-7.22.10.dist-info/METADATA +1077 -0
- codecin-7.22.10.dist-info/RECORD +202 -0
- codecin-7.22.10.dist-info/WHEEL +5 -0
- codecin-7.22.10.dist-info/entry_points.txt +5 -0
- codecin-7.22.10.dist-info/licenses/LICENSE +7 -0
- codecin-7.22.10.dist-info/top_level.txt +1 -0
codecin/crom.py
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
"""CROM 内存镜像与 CPUSA 二进制程序格式 (v5.9.0 段式内存)。
|
|
2
|
+
|
|
3
|
+
v5.9.0 起程序内存默认 1 GiB, 不再整块存储:
|
|
4
|
+
- CROM v4 / BIN v3: 只保存已分配 (非零) 的内存段;
|
|
5
|
+
- 旧格式 (CROM v3 / BIN v2, 整块镜像) 仍可读取, 不再写出。
|
|
6
|
+
|
|
7
|
+
CROM 优先调用 Go 原生库 (codecin.native) 进行压缩/解压, 无原生库时回退 zlib。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import struct
|
|
12
|
+
import zlib
|
|
13
|
+
from typing import TYPE_CHECKING, List, Optional, Tuple
|
|
14
|
+
|
|
15
|
+
from .errors import CPUSimulatorError
|
|
16
|
+
from .isa import Constants
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from .cpu import CPU
|
|
20
|
+
from .logger import Logger
|
|
21
|
+
from .memory import FastMemory
|
|
22
|
+
|
|
23
|
+
CROM_HEADER_SIZE = 16
|
|
24
|
+
# flags bit0: zlib 压缩 (v3/v4 通用)
|
|
25
|
+
CROM_FLAG_COMPRESS = 0x01
|
|
26
|
+
CROM_FLAG_MMU = 0x02 # 仅 v3 遗留格式: 尾部携带 MMU 页表元数据 (读取时忽略)
|
|
27
|
+
# v3 遗留格式解压余量 (MMU 尾部元数据)
|
|
28
|
+
CROM_MAX_TRAILER = 4 << 20
|
|
29
|
+
|
|
30
|
+
Seg = Tuple[int, bytes]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _pack_segments(segs: List[Seg]) -> bytes:
|
|
34
|
+
"""段表编码: 每段 addr u64 + len u64 + data (顺序拼接)。"""
|
|
35
|
+
out = bytearray()
|
|
36
|
+
for addr, data in segs:
|
|
37
|
+
out += struct.pack('<QQ', addr, len(data))
|
|
38
|
+
out += data
|
|
39
|
+
return bytes(out)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _unpack_segments(data: bytes, seg_count: int) -> List[Seg]:
|
|
43
|
+
segs: List[Seg] = []
|
|
44
|
+
pos = 0
|
|
45
|
+
for _ in range(seg_count):
|
|
46
|
+
if pos + 16 > len(data):
|
|
47
|
+
raise CPUSimulatorError("段表不完整 (文件损坏?)")
|
|
48
|
+
addr, seg_len = struct.unpack_from('<QQ', data, pos)
|
|
49
|
+
pos += 16
|
|
50
|
+
if pos + seg_len > len(data):
|
|
51
|
+
raise CPUSimulatorError("段数据不完整 (文件损坏?)")
|
|
52
|
+
segs.append((addr, bytes(data[pos:pos + seg_len])))
|
|
53
|
+
pos += seg_len
|
|
54
|
+
return segs
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# ==================== CROM 内存镜像 ====================
|
|
58
|
+
|
|
59
|
+
def save_crom(memory: 'FastMemory', path: str, compress: bool = True,
|
|
60
|
+
logger: Optional['Logger'] = None) -> None:
|
|
61
|
+
"""CROM v4: 段式内存镜像 (只存已分配页)。"""
|
|
62
|
+
segs = memory.snapshot_segments()
|
|
63
|
+
body = _pack_segments(segs)
|
|
64
|
+
flags = CROM_FLAG_COMPRESS if compress else 0x00
|
|
65
|
+
if compress:
|
|
66
|
+
body = zlib.compress(body, level=6)
|
|
67
|
+
checksum = zlib.crc32(body) & 0xFFFFFFFF
|
|
68
|
+
# 头部 16B: MAGIC 4B | ver u8 | flags u8 | seg_count u32 | checksum u32 | 保留 2B
|
|
69
|
+
header = (Constants.CROM_MAGIC
|
|
70
|
+
+ struct.pack('<B', Constants.CROM_VERSION)
|
|
71
|
+
+ struct.pack('<B', flags)
|
|
72
|
+
+ struct.pack('<I', len(segs))
|
|
73
|
+
+ struct.pack('<I', checksum)
|
|
74
|
+
+ b'\x00\x00')
|
|
75
|
+
packed = header + body
|
|
76
|
+
with open(path, 'wb') as f:
|
|
77
|
+
f.write(packed)
|
|
78
|
+
if logger:
|
|
79
|
+
logger.info(f".crom saved to {path} ({len(packed)} bytes, "
|
|
80
|
+
f"segments={len(segs)}, compressed={compress})")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def load_crom(memory: 'FastMemory', path: str,
|
|
84
|
+
logger: Optional['Logger'] = None) -> None:
|
|
85
|
+
with open(path, 'rb') as f:
|
|
86
|
+
data = f.read()
|
|
87
|
+
|
|
88
|
+
if len(data) < 8:
|
|
89
|
+
raise CPUSimulatorError(f".crom file too short: {len(data)} bytes")
|
|
90
|
+
|
|
91
|
+
if data[:4] != Constants.CROM_MAGIC:
|
|
92
|
+
# 旧版裸格式: 前 4 字节为 mem_size。
|
|
93
|
+
# 要求声明长度与文件实际内容一致, 否则任意文件 (例如 "NOTACROMFILE")
|
|
94
|
+
# 都会被静默当成内存镜像载入。
|
|
95
|
+
mem_size = struct.unpack('<I', data[:4])[0]
|
|
96
|
+
if mem_size > len(data) - 4:
|
|
97
|
+
raise CPUSimulatorError(
|
|
98
|
+
f"Not a .crom file: 声明的 mem_size={mem_size} "
|
|
99
|
+
f"超过文件实际内容 ({len(data) - 4} bytes)")
|
|
100
|
+
memory.load_bytes(0, data[4:4 + mem_size])
|
|
101
|
+
if logger:
|
|
102
|
+
logger.info(f"Loaded legacy .crom: {min(mem_size, len(data) - 4)} bytes")
|
|
103
|
+
return
|
|
104
|
+
|
|
105
|
+
version = data[4]
|
|
106
|
+
if version == Constants.CROM_VERSION:
|
|
107
|
+
_load_crom_v4(memory, data, logger)
|
|
108
|
+
return
|
|
109
|
+
if version == Constants.CROM_VERSION_V3:
|
|
110
|
+
_load_crom_v3(memory, data, logger)
|
|
111
|
+
return
|
|
112
|
+
raise CPUSimulatorError(f"Unsupported .crom version: {version}")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _load_crom_v4(memory: 'FastMemory', data: bytes,
|
|
116
|
+
logger: Optional['Logger']) -> None:
|
|
117
|
+
"""v4: flags u8 + 保留 3B | seg_count u32 | checksum u32 | 段表。"""
|
|
118
|
+
if len(data) < CROM_HEADER_SIZE:
|
|
119
|
+
raise CPUSimulatorError(".crom header incomplete")
|
|
120
|
+
flags = data[5]
|
|
121
|
+
compressed = bool(flags & CROM_FLAG_COMPRESS)
|
|
122
|
+
seg_count = struct.unpack_from('<I', data, 6)[0]
|
|
123
|
+
checksum = struct.unpack_from('<I', data, 10)[0]
|
|
124
|
+
body = data[CROM_HEADER_SIZE:]
|
|
125
|
+
if zlib.crc32(body) & 0xFFFFFFFF != checksum:
|
|
126
|
+
raise CPUSimulatorError(".crom checksum mismatch (file corrupted?)")
|
|
127
|
+
if compressed:
|
|
128
|
+
try:
|
|
129
|
+
body = zlib.decompress(body)
|
|
130
|
+
except zlib.error as e:
|
|
131
|
+
raise CPUSimulatorError(
|
|
132
|
+
f"Failed to decompress .crom: {e}") from e
|
|
133
|
+
segs = _unpack_segments(body, seg_count)
|
|
134
|
+
memory.load_segments(segs)
|
|
135
|
+
if logger:
|
|
136
|
+
logger.info(f"Loaded .crom v4: {len(segs)} segments, "
|
|
137
|
+
f"compressed={compressed}")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _load_crom_v3(memory: 'FastMemory', data: bytes,
|
|
141
|
+
logger: Optional['Logger']) -> None:
|
|
142
|
+
"""v3 遗留格式: 整块内存镜像 (+ 可选 MMU 尾部, 忽略)。"""
|
|
143
|
+
if len(data) < CROM_HEADER_SIZE:
|
|
144
|
+
raise CPUSimulatorError(".crom header incomplete")
|
|
145
|
+
mem_size = struct.unpack_from('<I', data, 5)[0]
|
|
146
|
+
flags = data[9]
|
|
147
|
+
compressed = bool(flags & CROM_FLAG_COMPRESS)
|
|
148
|
+
checksum = struct.unpack_from('<I', data, 10)[0]
|
|
149
|
+
body = data[CROM_HEADER_SIZE:]
|
|
150
|
+
if zlib.crc32(body) & 0xFFFFFFFF != checksum:
|
|
151
|
+
raise CPUSimulatorError(".crom checksum mismatch (file corrupted?)")
|
|
152
|
+
if compressed:
|
|
153
|
+
limit = mem_size + CROM_MAX_TRAILER
|
|
154
|
+
try:
|
|
155
|
+
d = zlib.decompressobj()
|
|
156
|
+
raw = d.decompress(body, limit)
|
|
157
|
+
if d.unconsumed_tail:
|
|
158
|
+
raise CPUSimulatorError(
|
|
159
|
+
f".crom 解压超过头部声明的大小 ({limit} bytes): 疑似损坏或恶意文件")
|
|
160
|
+
raw += d.flush()
|
|
161
|
+
except zlib.error as e:
|
|
162
|
+
raise CPUSimulatorError(
|
|
163
|
+
f"Failed to decompress .crom: {e}") from e
|
|
164
|
+
if len(raw) > limit:
|
|
165
|
+
raise CPUSimulatorError(
|
|
166
|
+
f".crom 解压超过头部声明的大小 ({limit} bytes)")
|
|
167
|
+
else:
|
|
168
|
+
raw = body
|
|
169
|
+
if len(raw) > mem_size + CROM_MAX_TRAILER:
|
|
170
|
+
raise CPUSimulatorError(
|
|
171
|
+
f".crom 载荷超过头部声明的大小 ({mem_size} bytes)")
|
|
172
|
+
memory.load_bytes(0, raw[:min(mem_size, len(raw))])
|
|
173
|
+
if flags & CROM_FLAG_MMU and logger:
|
|
174
|
+
logger.info(".crom v3 含 MMU 页表 (v5.9.0 起已移除 MMU), 忽略")
|
|
175
|
+
if logger:
|
|
176
|
+
logger.info(f"Loaded legacy .crom v3: {min(mem_size, len(raw))} bytes, "
|
|
177
|
+
f"compressed={compressed}")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# ==================== CPUSA 二进制程序 ====================
|
|
181
|
+
# v3 (当前): MAGIC 5B + ver u8 + mem_size u64 + entry u32 + sp u64 +
|
|
182
|
+
# heap_base u64 + bc_len u32 + seg_count u32 + 保留 8B +
|
|
183
|
+
# 段表 (addr u64 + len u64 + data) + bytecode
|
|
184
|
+
# v2 (遗留): MAGIC 5B + ver u8 + mem_size u32 + entry u32 + sp u64 +
|
|
185
|
+
# bc_len u32 + 保留 8B + 整块内存镜像 + bytecode
|
|
186
|
+
|
|
187
|
+
BIN_V3_HEADER = 5 + 1 + 8 + 4 + 8 + 8 + 4 + 4 + 8 # 50
|
|
188
|
+
|
|
189
|
+
#: v2 容器头长度: MAGIC 5 + ver 1 + mem_size u32 + entry u32 + sp u64 +
|
|
190
|
+
#: bc_len u32 + 保留 8B。
|
|
191
|
+
BIN_V2_HEADER = 34
|
|
192
|
+
#: 与 Go 引擎 vm.push() / SYS ALLOCFRAME 的栈-堆隔离区一致。SP 必须高于
|
|
193
|
+
#: heap_base + 该值, 否则首条 PUSH/ALLOCFRAME 就会被判为栈堆碰撞。
|
|
194
|
+
BIN_STACK_GUARD = 4096
|
|
195
|
+
#: v5.9.0 之前的默认内存 (64 KiB): 旧 BIN v2 的迁移提示用。
|
|
196
|
+
LEGACY_BIN_MEM_SIZE = 64 * 1024
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _bin_error_name(path: Optional[str]) -> str:
|
|
200
|
+
return f" '{os.path.basename(path)}'" if path else ""
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _bin_actions(path: Optional[str], mem_size: int) -> List[str]:
|
|
204
|
+
"""旧版 BIN 布局不兼容时的可执行建议 (两行)。"""
|
|
205
|
+
target = os.path.basename(path) if path else "<程序>.bin"
|
|
206
|
+
return [
|
|
207
|
+
"请任选其一:",
|
|
208
|
+
" 1) 用当前版本重新编译源码: "
|
|
209
|
+
"codecin <源码>.cin --compile -o <新文件>.bin",
|
|
210
|
+
f" 2) 用与字节码一致的内存布局运行: "
|
|
211
|
+
f"codecin {target} --mem-size {mem_size}",
|
|
212
|
+
]
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _bin_header_layout_error(version: int, mem_size: int, sp: int,
|
|
216
|
+
heap_base: int, reason: str) -> CPUSimulatorError:
|
|
217
|
+
"""头部自相矛盾 (SP/heap/mem_size 越界): 在加载阶段直接拒绝。"""
|
|
218
|
+
return CPUSimulatorError(
|
|
219
|
+
f"BIN v{version} 头部记录的栈/堆布局非法: {reason}。\n"
|
|
220
|
+
f" mem_size={mem_size} bytes (0x{mem_size:x}), sp=0x{sp:x}, "
|
|
221
|
+
f"heap_base=0x{heap_base:x}\n"
|
|
222
|
+
" 该文件可能已损坏, 或由不兼容的工具链生成; "
|
|
223
|
+
"请用当前版本重新编译源码后重试。")
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _legacy_bin_layout_error(path: Optional[str], mem_size: int, sp: int,
|
|
227
|
+
heap_base: int, runtime_mem: int,
|
|
228
|
+
runtime_heap: int) -> CPUSimulatorError:
|
|
229
|
+
"""v2 文件记录的布局与当前 --mem-size 布局不兼容。
|
|
230
|
+
|
|
231
|
+
典型场景: v5.9.0 之前默认 64 KiB 内存编译的 BIN (SP≈0xfff0) 被 v5.9.0+
|
|
232
|
+
的默认 1 GiB 布局加载, heap_base 变成 0x20000000, SP 低于堆警戒线。
|
|
233
|
+
必须在这里拦住: 否则执行首条 PUSH/ALLOCFRAME 才会报
|
|
234
|
+
"Stack overflow (collides with heap)", 很容易被误解为真实栈溢出。
|
|
235
|
+
"""
|
|
236
|
+
lines = [
|
|
237
|
+
f"无法加载旧版 BIN v2 字节码{_bin_error_name(path)}: "
|
|
238
|
+
"其初始 SP 约定与当前内存布局不兼容。",
|
|
239
|
+
f" 文件头布局: mem_size={mem_size} bytes (0x{mem_size:x}), "
|
|
240
|
+
f"sp=0x{sp:x}, 期望 heap_base=0x{heap_base:x}",
|
|
241
|
+
f" 当前运行布局: mem_size={runtime_mem} bytes (0x{runtime_mem:x}), "
|
|
242
|
+
f"heap_base=0x{runtime_heap:x}",
|
|
243
|
+
" BIN v2 只记录 SP、不记录 heap_base;旧运行时固定按 "
|
|
244
|
+
"heap_base = mem_size // 2 计算堆基址。",
|
|
245
|
+
]
|
|
246
|
+
if sp < runtime_heap + BIN_STACK_GUARD + Constants.STACK_SLOT:
|
|
247
|
+
lines.extend([
|
|
248
|
+
" 按当前布局执行时 SP 低于 heap_base + 4096 的栈保护线, "
|
|
249
|
+
"首条 PUSH/ALLOCFRAME 会被误报为",
|
|
250
|
+
' "Stack overflow (collides with heap)" (并非真实栈写满)。',
|
|
251
|
+
])
|
|
252
|
+
else:
|
|
253
|
+
lines.append(
|
|
254
|
+
f" 当前布局会把堆基址从 0x{heap_base:x} 抬高到 "
|
|
255
|
+
f"0x{runtime_heap:x}, 改变字节码编译时的栈/堆边界。")
|
|
256
|
+
if mem_size == LEGACY_BIN_MEM_SIZE:
|
|
257
|
+
lines.append(
|
|
258
|
+
" 该字节码可能由 v5.9.0 之前的旧版本 (默认 64 KB 内存) 编译; "
|
|
259
|
+
"格式可读不等于内存布局兼容。")
|
|
260
|
+
else:
|
|
261
|
+
lines.append(
|
|
262
|
+
" 该字节码的初始 SP 约定与当前 --mem-size 布局不匹配; "
|
|
263
|
+
"格式可读不等于内存布局兼容。")
|
|
264
|
+
lines.extend(_bin_actions(path, mem_size))
|
|
265
|
+
return CPUSimulatorError("\n".join(lines))
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _validate_bin_stack_layout(version: int, mem_size: int, sp: int,
|
|
269
|
+
heap_base: int) -> None:
|
|
270
|
+
"""校验头部的 mem_size / SP / heap_base 是否自洽。
|
|
271
|
+
|
|
272
|
+
这里只做与运行环境无关的检查; v2 与当前 --mem-size 的差异由
|
|
273
|
+
:func:`_legacy_bin_layout_error` 处理。
|
|
274
|
+
"""
|
|
275
|
+
if mem_size < 256:
|
|
276
|
+
raise _bin_header_layout_error(
|
|
277
|
+
version, mem_size, sp, heap_base,
|
|
278
|
+
"mem_size 过小 (最小 256 bytes)")
|
|
279
|
+
if mem_size > (1 << 40):
|
|
280
|
+
raise _bin_header_layout_error(
|
|
281
|
+
version, mem_size, sp, heap_base,
|
|
282
|
+
"mem_size 超出引擎上限 (1 TiB)")
|
|
283
|
+
if heap_base > mem_size - Constants.STACK_SLOT:
|
|
284
|
+
raise _bin_header_layout_error(
|
|
285
|
+
version, mem_size, sp, heap_base,
|
|
286
|
+
"heap_base 超出内存范围")
|
|
287
|
+
if sp < Constants.STACK_SLOT or sp > mem_size - Constants.STACK_SLOT:
|
|
288
|
+
raise _bin_header_layout_error(
|
|
289
|
+
version, mem_size, sp, heap_base,
|
|
290
|
+
"SP 超出内存范围或未给栈槽位留出空间")
|
|
291
|
+
if sp < heap_base:
|
|
292
|
+
raise _bin_header_layout_error(
|
|
293
|
+
version, mem_size, sp, heap_base,
|
|
294
|
+
"SP 低于 heap_base")
|
|
295
|
+
# 只有内存本身足够大、能容纳 4 KiB 栈堆隔离区时才强制守卫线;
|
|
296
|
+
# 极小的 --mem-size 布局 (例如只跑 HALT 的 .bin) 不应仅因此被拒绝。
|
|
297
|
+
min_sp = heap_base + BIN_STACK_GUARD + Constants.STACK_SLOT
|
|
298
|
+
if min_sp <= mem_size - Constants.STACK_SLOT and sp < min_sp:
|
|
299
|
+
raise _bin_header_layout_error(
|
|
300
|
+
version, mem_size, sp, heap_base,
|
|
301
|
+
"SP 低于堆警戒线 (heap_base + 4096)")
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def dump_bin(cpu: 'CPU') -> bytes:
|
|
305
|
+
"""把已编译的 CPU 状态序列化为 BIN v3 字节流 (不落盘)。
|
|
306
|
+
|
|
307
|
+
``.sdgcc`` 容器的 ``CODE`` 段就是本函数的返回值, 因此容器与旧 ``.bin``
|
|
308
|
+
在字节层面完全一致。
|
|
309
|
+
"""
|
|
310
|
+
from .native import encode_program
|
|
311
|
+
all_labels = dict(cpu.labels)
|
|
312
|
+
all_labels.update(cpu.data_labels)
|
|
313
|
+
bytecode = encode_program(cpu.instructions, cpu.entry_pc, all_labels)
|
|
314
|
+
segs = cpu.memory.snapshot_segments()
|
|
315
|
+
return b''.join((
|
|
316
|
+
Constants.MAGIC_NUMBER, # 5B
|
|
317
|
+
struct.pack('<B', Constants.BIN_VERSION), # 1B
|
|
318
|
+
struct.pack('<Q', len(cpu.memory)), # 8B
|
|
319
|
+
struct.pack('<I', cpu.entry_pc), # 4B
|
|
320
|
+
struct.pack('<Q', cpu.sp), # 8B
|
|
321
|
+
struct.pack('<Q', cpu.heap_base), # 8B
|
|
322
|
+
struct.pack('<I', len(bytecode)), # 4B
|
|
323
|
+
struct.pack('<I', len(segs)), # 4B
|
|
324
|
+
b'\x00' * 8, # 保留
|
|
325
|
+
_pack_segments(segs),
|
|
326
|
+
bytecode,
|
|
327
|
+
))
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def save_bin(cpu: 'CPU', path: str, logger: Optional['Logger'] = None) -> None:
|
|
331
|
+
data = dump_bin(cpu)
|
|
332
|
+
with open(path, 'wb') as f:
|
|
333
|
+
f.write(data)
|
|
334
|
+
if logger:
|
|
335
|
+
logger.info(f"Binary saved to {path} ({len(data)} bytes)")
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def read_code(path: str) -> bytes:
|
|
339
|
+
"""读取 ``.sdgcc`` / ``.bin`` 并返回其中的 BIN v3 字节流。"""
|
|
340
|
+
from . import sdgcc
|
|
341
|
+
with open(path, 'rb') as f:
|
|
342
|
+
data = f.read()
|
|
343
|
+
code, _container = sdgcc.unwrap(data)
|
|
344
|
+
return code
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def load_bin(cpu: 'CPU', path: str) -> None:
|
|
348
|
+
with open(path, 'rb') as f:
|
|
349
|
+
data = f.read()
|
|
350
|
+
|
|
351
|
+
from . import sdgcc
|
|
352
|
+
if sdgcc.is_sdgcc(data):
|
|
353
|
+
data = sdgcc.parse(data).code
|
|
354
|
+
|
|
355
|
+
if len(data) < 6 or data[:5] != Constants.MAGIC_NUMBER:
|
|
356
|
+
raise CPUSimulatorError("Invalid binary file (bad magic)")
|
|
357
|
+
version = data[5]
|
|
358
|
+
if version == Constants.BIN_VERSION:
|
|
359
|
+
_load_bin_v3(cpu, data, path)
|
|
360
|
+
return
|
|
361
|
+
if version == Constants.BIN_VERSION_V2:
|
|
362
|
+
_load_bin_v2(cpu, data, path)
|
|
363
|
+
return
|
|
364
|
+
raise CPUSimulatorError(f"Unsupported binary version: {version}")
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _load_bin_v3(cpu: 'CPU', data: bytes, path: Optional[str] = None) -> None:
|
|
368
|
+
from .native import decode_program
|
|
369
|
+
if len(data) < BIN_V3_HEADER:
|
|
370
|
+
raise CPUSimulatorError("BIN v3 头部不完整 (文件损坏?)")
|
|
371
|
+
mem_size = struct.unpack_from('<Q', data, 6)[0]
|
|
372
|
+
entry = struct.unpack_from('<I', data, 14)[0]
|
|
373
|
+
sp = struct.unpack_from('<Q', data, 18)[0]
|
|
374
|
+
heap_base = struct.unpack_from('<Q', data, 26)[0]
|
|
375
|
+
bc_len = struct.unpack_from('<I', data, 34)[0]
|
|
376
|
+
seg_count = struct.unpack_from('<I', data, 38)[0]
|
|
377
|
+
|
|
378
|
+
_validate_bin_stack_layout(3, mem_size, sp, heap_base)
|
|
379
|
+
|
|
380
|
+
segs = _unpack_segments(data[BIN_V3_HEADER:], seg_count)
|
|
381
|
+
packed_segs = _pack_segments(segs)
|
|
382
|
+
bytecode_off = BIN_V3_HEADER + len(packed_segs)
|
|
383
|
+
if bytecode_off + bc_len > len(data):
|
|
384
|
+
raise CPUSimulatorError("BIN v3 字节码不完整 (文件损坏?)")
|
|
385
|
+
# 段表声明的内容不能越过头部声明的内存大小。
|
|
386
|
+
for addr, seg_data in segs:
|
|
387
|
+
if addr + len(seg_data) > mem_size:
|
|
388
|
+
raise CPUSimulatorError(
|
|
389
|
+
f"BIN v3 段地址越界: segment 0x{addr:x}+{len(seg_data)} "
|
|
390
|
+
f"超出头部 mem_size={mem_size} bytes (文件损坏?)")
|
|
391
|
+
bytecode = data[bytecode_off:bytecode_off + bc_len]
|
|
392
|
+
|
|
393
|
+
if mem_size > len(cpu.memory):
|
|
394
|
+
cpu.memory.resize(mem_size)
|
|
395
|
+
cpu.config.mem_size = mem_size
|
|
396
|
+
cpu.memory.load_segments(segs)
|
|
397
|
+
cpu.instructions, cpu.entry_pc = decode_program(bytecode)
|
|
398
|
+
cpu.pc = entry
|
|
399
|
+
cpu.sp = sp
|
|
400
|
+
cpu.heap_base = heap_base
|
|
401
|
+
cpu.heap_ptr = heap_base
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _load_bin_v2(cpu: 'CPU', data: bytes, path: Optional[str] = None) -> None:
|
|
405
|
+
"""v2 遗留格式: 整块内存镜像。
|
|
406
|
+
|
|
407
|
+
头部 34B: MAGIC 5 + ver 1 + mem_size u32 + entry u32 + sp u64 +
|
|
408
|
+
bc_len u32 + 保留 8B, 之后是镜像与字节码。
|
|
409
|
+
|
|
410
|
+
v2 不记录 heap_base: 旧运行时固定按 ``heap_base = mem_size // 2`` 布局。
|
|
411
|
+
因此只有当当前 ``--mem-size`` 与头部声明完全一致时才能复现旧布局;
|
|
412
|
+
不一致时在加载阶段给出明确错误 (而不是让首条 PUSH 报假栈溢出)。
|
|
413
|
+
"""
|
|
414
|
+
from .native import decode_program
|
|
415
|
+
if len(data) < BIN_V2_HEADER:
|
|
416
|
+
raise CPUSimulatorError("BIN v2 头部不完整 (文件损坏?)")
|
|
417
|
+
mem_size = struct.unpack_from('<I', data, 6)[0]
|
|
418
|
+
entry = struct.unpack_from('<I', data, 10)[0]
|
|
419
|
+
sp = struct.unpack_from('<Q', data, 14)[0]
|
|
420
|
+
bc_len = struct.unpack_from('<I', data, 22)[0]
|
|
421
|
+
expected_heap = mem_size // 2
|
|
422
|
+
|
|
423
|
+
_validate_bin_stack_layout(2, mem_size, sp, expected_heap)
|
|
424
|
+
|
|
425
|
+
runtime_mem = len(cpu.memory)
|
|
426
|
+
if runtime_mem > mem_size:
|
|
427
|
+
# 不再静默地把旧 BIN 放进更大的 1 GiB 布局: heap_base 会从
|
|
428
|
+
# mem_size//2 抬到 runtime_mem//2, 与文件里的 SP 冲突。
|
|
429
|
+
raise _legacy_bin_layout_error(
|
|
430
|
+
path, mem_size, sp, expected_heap, runtime_mem, cpu.heap_ptr)
|
|
431
|
+
if runtime_mem < mem_size:
|
|
432
|
+
cpu.memory.resize(mem_size)
|
|
433
|
+
cpu.config.mem_size = mem_size
|
|
434
|
+
|
|
435
|
+
image_end = BIN_V2_HEADER + mem_size
|
|
436
|
+
if image_end + bc_len > len(data):
|
|
437
|
+
raise CPUSimulatorError(
|
|
438
|
+
f"BIN v2 数据不完整 (需要 {image_end + bc_len} bytes, "
|
|
439
|
+
f"实际 {len(data)} bytes)")
|
|
440
|
+
mem_image = data[BIN_V2_HEADER:image_end]
|
|
441
|
+
bytecode = data[image_end:image_end + bc_len]
|
|
442
|
+
|
|
443
|
+
cpu.memory.load_bytes(0, mem_image)
|
|
444
|
+
cpu.instructions, cpu.entry_pc = decode_program(bytecode)
|
|
445
|
+
cpu.pc = entry
|
|
446
|
+
cpu.sp = sp
|
|
447
|
+
# 与旧运行时一致: 堆基址由内存大小决定, v2 文件没有该字段。
|
|
448
|
+
cpu.heap_base = expected_heap
|
|
449
|
+
cpu.heap_ptr = expected_heap
|