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/sdgcc.py
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
"""``.sdgcc`` —— Code CIN 编译产物容器 (BIN v3 的带元数据封装)。
|
|
2
|
+
|
|
3
|
+
自 v6.5 起 ``.sdgcc`` 是**默认产物**: 它把一份完整的 BIN v3 字节流放在
|
|
4
|
+
``CODE`` 段里, 再附加元数据、符号与源码清单。这样做的目的:
|
|
5
|
+
|
|
6
|
+
* **向后兼容**: ``CODE`` 段逐字节等于旧 ``.bin``, 任何只认 BIN v3 的读取器
|
|
7
|
+
都可以直接消费; ``.bin`` 也仍是**合法输入**, :func:`unwrap` 会原样透传。
|
|
8
|
+
* **可自描述**: 单文件/多文件模式、目标平台、入口、优化级别、依赖文件都在
|
|
9
|
+
文件内, 不再靠文件名或旁挂 JSON 猜测。
|
|
10
|
+
* **零依赖解析**: 固定 28 字节头 + 24 字节/段的表, 顺序读一遍即可, 不需要
|
|
11
|
+
zip/TOML 解析器参与装载 (元数据按需解析)。
|
|
12
|
+
|
|
13
|
+
二进制布局 (小端)::
|
|
14
|
+
|
|
15
|
+
offset size field
|
|
16
|
+
0 5 magic b'SDGCC'
|
|
17
|
+
5 1 version (1 = 未压缩, 2 = 支持按段压缩)
|
|
18
|
+
6 2 flags (bit0 多文件, bit1 符号表, bit2 源码清单,
|
|
19
|
+
bit3 至少一个压缩段)
|
|
20
|
+
8 16 target (ASCII, NUL 填充; 'host' = 构建机)
|
|
21
|
+
24 4 section count N
|
|
22
|
+
28 24*N section table: name[8] | offset u64 | size u64
|
|
23
|
+
... payload
|
|
24
|
+
|
|
25
|
+
``size`` 的最高位 (bit63) 表示该段使用 zlib 压缩; 此时后 63 位是**存储长度**,
|
|
26
|
+
段内容前 4 字节为原始长度。``CODE`` 段永不压缩 (保证旧 BIN 读取器兼容)。
|
|
27
|
+
|
|
28
|
+
段名: ``CODE`` (必需, BIN v3), ``META`` (TOML), ``SYMS``, ``SRCS``。
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
import os
|
|
32
|
+
import struct
|
|
33
|
+
import zlib
|
|
34
|
+
from dataclasses import dataclass, field
|
|
35
|
+
from datetime import datetime, timezone
|
|
36
|
+
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
|
|
37
|
+
|
|
38
|
+
from .isa import Constants
|
|
39
|
+
|
|
40
|
+
__all__ = [
|
|
41
|
+
'SDGCC_MAGIC',
|
|
42
|
+
'SDGCC_VERSION',
|
|
43
|
+
'SDGCC_VERSION_COMPRESSED',
|
|
44
|
+
'Sdgcc',
|
|
45
|
+
'SdgccError',
|
|
46
|
+
'build',
|
|
47
|
+
'describe',
|
|
48
|
+
'dump',
|
|
49
|
+
'is_sdgcc',
|
|
50
|
+
'load',
|
|
51
|
+
'parse',
|
|
52
|
+
'read_code',
|
|
53
|
+
'save',
|
|
54
|
+
'save_program',
|
|
55
|
+
'unwrap',
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
#: 容器 magic (5 字节, 与 BIN 的 ``CPUSA`` 等长, 便于魔数嗅探)。
|
|
59
|
+
SDGCC_MAGIC = b'SDGCC'
|
|
60
|
+
#: 默认容器版本 (未压缩)。
|
|
61
|
+
SDGCC_VERSION = 1
|
|
62
|
+
#: 支持按段压缩的容器版本。
|
|
63
|
+
SDGCC_VERSION_COMPRESSED = 2
|
|
64
|
+
#: 解析器接受的最大版本。
|
|
65
|
+
SDGCC_MAX_VERSION = SDGCC_VERSION_COMPRESSED
|
|
66
|
+
|
|
67
|
+
#: 单文件模式 / 多文件模式。
|
|
68
|
+
MODE_SINGLE = 'single'
|
|
69
|
+
MODE_MULTI = 'multi'
|
|
70
|
+
|
|
71
|
+
FLAG_MULTI_FILE = 0x0001
|
|
72
|
+
FLAG_SYMBOLS = 0x0002
|
|
73
|
+
FLAG_SOURCES = 0x0004
|
|
74
|
+
FLAG_COMPRESSED = 0x0008
|
|
75
|
+
|
|
76
|
+
#: 段表 size 字段最高位 = 该段已压缩。
|
|
77
|
+
_ENTRY_COMPRESSED = 1 << 63
|
|
78
|
+
|
|
79
|
+
TARGET_HOST = 'host'
|
|
80
|
+
|
|
81
|
+
SECTION_CODE = 'CODE'
|
|
82
|
+
SECTION_META = 'META'
|
|
83
|
+
SECTION_SYMS = 'SYMS'
|
|
84
|
+
SECTION_SRCS = 'SRCS'
|
|
85
|
+
|
|
86
|
+
_FIXED = struct.Struct('<5sBH16s') # magic, version, flags, target[16]
|
|
87
|
+
_COUNT = struct.Struct('<I')
|
|
88
|
+
_ENTRY = struct.Struct('<8sQQ') # name, offset, size
|
|
89
|
+
|
|
90
|
+
HEADER_SIZE = _FIXED.size + _COUNT.size # 28
|
|
91
|
+
ENTRY_SIZE = _ENTRY.size # 24
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class SdgccError(ValueError):
|
|
95
|
+
"""``.sdgcc`` 容器损坏/版本不支持。"""
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass
|
|
99
|
+
class Sdgcc:
|
|
100
|
+
"""解析后的 ``.sdgcc`` 容器。"""
|
|
101
|
+
|
|
102
|
+
version: int
|
|
103
|
+
flags: int
|
|
104
|
+
target: str
|
|
105
|
+
sections: Dict[str, bytes] = field(default_factory=dict)
|
|
106
|
+
meta: Dict[str, Any] = field(default_factory=dict)
|
|
107
|
+
#: name -> (offset, stored_size, logical_size, compressed)
|
|
108
|
+
entries: Dict[str, Tuple[int, int, int, bool]] = field(
|
|
109
|
+
default_factory=dict)
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def multi_file(self) -> bool:
|
|
113
|
+
return bool(self.flags & FLAG_MULTI_FILE)
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def code(self) -> bytes:
|
|
117
|
+
return self.sections[SECTION_CODE]
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def symbols(self) -> List[Tuple[int, str]]:
|
|
121
|
+
raw = self.sections.get(SECTION_SYMS)
|
|
122
|
+
if not raw:
|
|
123
|
+
return []
|
|
124
|
+
return _decode_symbols(raw)
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def sources(self) -> List[str]:
|
|
128
|
+
raw = self.sections.get(SECTION_SRCS)
|
|
129
|
+
if not raw:
|
|
130
|
+
return []
|
|
131
|
+
return _decode_sources(raw)
|
|
132
|
+
|
|
133
|
+
@property
|
|
134
|
+
def size(self) -> int:
|
|
135
|
+
return len(self.code)
|
|
136
|
+
|
|
137
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
138
|
+
build_info = self.meta.get('build') or {}
|
|
139
|
+
return {
|
|
140
|
+
'format': self.version,
|
|
141
|
+
'mode': MODE_MULTI if self.multi_file else MODE_SINGLE,
|
|
142
|
+
'target': self.target,
|
|
143
|
+
'symbols': len(self.symbols),
|
|
144
|
+
'sources': list(self.sources),
|
|
145
|
+
'code': self.size,
|
|
146
|
+
'entry': build_info.get('entry'),
|
|
147
|
+
'optimize': build_info.get('optimize'),
|
|
148
|
+
'mem_size': build_info.get('mem_size'),
|
|
149
|
+
'bin_version': build_info.get('bin_version'),
|
|
150
|
+
'bytecode_len': build_info.get('bytecode_len'),
|
|
151
|
+
'compressed': sum(1 for item in self.entries.values() if item[3]),
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
# ==================== 编码 ====================
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _pad_name(name: str) -> bytes:
|
|
159
|
+
raw = name.encode('ascii', 'replace')[:8]
|
|
160
|
+
return raw + b'\x00' * (8 - len(raw))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _encode_symbols(symbols: Iterable[Tuple[int, str]]) -> bytes:
|
|
164
|
+
items = sorted(((int(pc), str(name)) for pc, name in symbols),
|
|
165
|
+
key=lambda item: item[0])
|
|
166
|
+
out = [_COUNT.pack(len(items))]
|
|
167
|
+
for pc, name in items:
|
|
168
|
+
raw = name.encode('utf-8')
|
|
169
|
+
out.append(struct.pack('<IH', pc, len(raw)))
|
|
170
|
+
out.append(raw)
|
|
171
|
+
return b''.join(out)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _decode_symbols(raw: bytes) -> List[Tuple[int, str]]:
|
|
175
|
+
if len(raw) < 4:
|
|
176
|
+
raise SdgccError('SYMS 段不完整')
|
|
177
|
+
count = struct.unpack_from('<I', raw, 0)[0]
|
|
178
|
+
offset = 4
|
|
179
|
+
out: List[Tuple[int, str]] = []
|
|
180
|
+
for _ in range(count):
|
|
181
|
+
if offset + 6 > len(raw):
|
|
182
|
+
raise SdgccError('SYMS 段被截断')
|
|
183
|
+
pc, length = struct.unpack_from('<IH', raw, offset)
|
|
184
|
+
offset += 6
|
|
185
|
+
if offset + length > len(raw):
|
|
186
|
+
raise SdgccError('SYMS 段符号名被截断')
|
|
187
|
+
out.append((pc, raw[offset:offset + length].decode('utf-8', 'replace')))
|
|
188
|
+
offset += length
|
|
189
|
+
return out
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _encode_sources(sources: Sequence[str]) -> bytes:
|
|
193
|
+
items = [str(s) for s in sources]
|
|
194
|
+
out = [_COUNT.pack(len(items))]
|
|
195
|
+
for item in items:
|
|
196
|
+
raw = item.encode('utf-8')
|
|
197
|
+
if len(raw) > 0xFFFF:
|
|
198
|
+
raise SdgccError(f'源码路径过长: {item!r}')
|
|
199
|
+
out.append(struct.pack('<H', len(raw)))
|
|
200
|
+
out.append(raw)
|
|
201
|
+
return b''.join(out)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _decode_sources(raw: bytes) -> List[str]:
|
|
205
|
+
if len(raw) < 4:
|
|
206
|
+
raise SdgccError('SRCS 段不完整')
|
|
207
|
+
count = struct.unpack_from('<I', raw, 0)[0]
|
|
208
|
+
offset = 4
|
|
209
|
+
out: List[str] = []
|
|
210
|
+
for _ in range(count):
|
|
211
|
+
if offset + 2 > len(raw):
|
|
212
|
+
raise SdgccError('SRCS 段被截断')
|
|
213
|
+
length = struct.unpack_from('<H', raw, offset)[0]
|
|
214
|
+
offset += 2
|
|
215
|
+
if offset + length > len(raw):
|
|
216
|
+
raise SdgccError('SRCS 段路径被截断')
|
|
217
|
+
out.append(raw[offset:offset + length].decode('utf-8', 'replace'))
|
|
218
|
+
offset += length
|
|
219
|
+
return out
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _default_meta(target: str, multi_file: bool) -> Dict[str, Any]:
|
|
223
|
+
return {
|
|
224
|
+
'sdgcc': {
|
|
225
|
+
'format': SDGCC_VERSION,
|
|
226
|
+
'mode': MODE_MULTI if multi_file else MODE_SINGLE,
|
|
227
|
+
'target': target,
|
|
228
|
+
'created': datetime.now(timezone.utc)
|
|
229
|
+
.replace(microsecond=0).isoformat(),
|
|
230
|
+
},
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _dumps_meta(meta: Dict[str, Any]) -> bytes:
|
|
235
|
+
from .packaging.toml import dumps
|
|
236
|
+
return dumps(meta).encode('utf-8')
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _loads_meta(raw: bytes) -> Dict[str, Any]:
|
|
240
|
+
from .packaging.toml import loads
|
|
241
|
+
try:
|
|
242
|
+
data = loads(raw.decode('utf-8'))
|
|
243
|
+
except Exception as e: # noqa: BLE001 - 统一转换为 SdgccError
|
|
244
|
+
raise SdgccError(f'META 段不是合法 TOML: {e}') from e
|
|
245
|
+
if not isinstance(data, dict):
|
|
246
|
+
raise SdgccError('META 段顶层必须是表')
|
|
247
|
+
return data
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def build(code: bytes,
|
|
251
|
+
*,
|
|
252
|
+
target: str = TARGET_HOST,
|
|
253
|
+
multi_file: bool = True,
|
|
254
|
+
meta: Optional[Dict[str, Any]] = None,
|
|
255
|
+
symbols: Optional[Iterable[Tuple[int, str]]] = None,
|
|
256
|
+
sources: Optional[Sequence[str]] = None,
|
|
257
|
+
version: int = SDGCC_VERSION,
|
|
258
|
+
compress: bool = False) -> bytes:
|
|
259
|
+
"""把 BIN v3 字节流封装为 ``.sdgcc``。
|
|
260
|
+
|
|
261
|
+
``code`` 必须是完整 BIN v3 镜像 (以 ``CPUSA`` 开头); 传入 ``.bin`` 原始
|
|
262
|
+
字节即可, 容器不会改动其内容。
|
|
263
|
+
"""
|
|
264
|
+
if not isinstance(code, (bytes, bytearray, memoryview)):
|
|
265
|
+
raise SdgccError('code 必须是 bytes')
|
|
266
|
+
code = bytes(code)
|
|
267
|
+
if len(code) < 6 or code[:5] != Constants.MAGIC_NUMBER:
|
|
268
|
+
raise SdgccError('CODE 必须以 BIN magic (CPUSA) 开头')
|
|
269
|
+
if code[5] not in (Constants.BIN_VERSION, Constants.BIN_VERSION_V2):
|
|
270
|
+
raise SdgccError(f'CODE 以不支持的 BIN 版本开头: {code[5]}')
|
|
271
|
+
|
|
272
|
+
version_out = SDGCC_VERSION_COMPRESSED if compress else version
|
|
273
|
+
payload: List[Tuple[str, bytes]] = [(SECTION_CODE, code)]
|
|
274
|
+
info = dict(meta or _default_meta(target, multi_file))
|
|
275
|
+
info.setdefault('sdgcc', {})
|
|
276
|
+
if not isinstance(info.get('sdgcc'), dict):
|
|
277
|
+
raise SdgccError('meta[sdgcc] 必须是表')
|
|
278
|
+
info['sdgcc']['format'] = version_out
|
|
279
|
+
info['sdgcc']['mode'] = MODE_MULTI if multi_file else MODE_SINGLE
|
|
280
|
+
info['sdgcc'].setdefault('target', target)
|
|
281
|
+
payload.append((SECTION_META, _dumps_meta(info)))
|
|
282
|
+
|
|
283
|
+
flags = FLAG_MULTI_FILE if multi_file else 0
|
|
284
|
+
if symbols:
|
|
285
|
+
payload.append((SECTION_SYMS, _encode_symbols(symbols)))
|
|
286
|
+
flags |= FLAG_SYMBOLS
|
|
287
|
+
if sources:
|
|
288
|
+
payload.append((SECTION_SRCS, _encode_sources(sources)))
|
|
289
|
+
flags |= FLAG_SOURCES
|
|
290
|
+
|
|
291
|
+
table_size = HEADER_SIZE + ENTRY_SIZE * len(payload)
|
|
292
|
+
offset = table_size
|
|
293
|
+
table: List[bytes] = []
|
|
294
|
+
body = bytearray()
|
|
295
|
+
for name, data in payload:
|
|
296
|
+
stored = data
|
|
297
|
+
packed = False
|
|
298
|
+
if compress and name != SECTION_CODE and len(data) >= 16:
|
|
299
|
+
blob = zlib.compress(data, 9)
|
|
300
|
+
if len(blob) + 4 < len(data):
|
|
301
|
+
stored = struct.pack('<I', len(data)) + blob
|
|
302
|
+
packed = True
|
|
303
|
+
flags |= FLAG_COMPRESSED
|
|
304
|
+
size_field = len(stored) | (_ENTRY_COMPRESSED if packed else 0)
|
|
305
|
+
table.append(_ENTRY.pack(_pad_name(name), offset, size_field))
|
|
306
|
+
body += stored
|
|
307
|
+
offset += len(stored)
|
|
308
|
+
header = (_FIXED.pack(SDGCC_MAGIC, version_out, flags,
|
|
309
|
+
target.encode('ascii', 'replace')[:16].ljust(16, b'\x00'))
|
|
310
|
+
+ _COUNT.pack(len(payload)))
|
|
311
|
+
return header + b''.join(table) + bytes(body)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
# ==================== 解码 ====================
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def is_sdgcc(data: bytes) -> bool:
|
|
318
|
+
return len(data) >= 5 and data[:5] == SDGCC_MAGIC
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def parse(data: bytes) -> Sdgcc:
|
|
322
|
+
"""解析 ``.sdgcc`` 字节流并做结构校验。"""
|
|
323
|
+
if not is_sdgcc(data):
|
|
324
|
+
raise SdgccError('不是 .sdgcc (magic 不匹配)')
|
|
325
|
+
if len(data) < HEADER_SIZE:
|
|
326
|
+
raise SdgccError('.sdgcc 头部不完整')
|
|
327
|
+
magic, version, flags, raw_target = _FIXED.unpack_from(data, 0)
|
|
328
|
+
if version > SDGCC_MAX_VERSION or version == 0:
|
|
329
|
+
raise SdgccError(f'不支持的 .sdgcc 版本: {version}')
|
|
330
|
+
count = _COUNT.unpack_from(data, HEADER_SIZE - _COUNT.size)[0]
|
|
331
|
+
if count == 0 or count > 64:
|
|
332
|
+
raise SdgccError(f'段表数量异常: {count}')
|
|
333
|
+
|
|
334
|
+
table_end = HEADER_SIZE + ENTRY_SIZE * count
|
|
335
|
+
if table_end > len(data):
|
|
336
|
+
raise SdgccError('段表被截断')
|
|
337
|
+
|
|
338
|
+
sections: Dict[str, bytes] = {}
|
|
339
|
+
entries: Dict[str, Tuple[int, int, int, bool]] = {}
|
|
340
|
+
order: List[Tuple[int, int]] = []
|
|
341
|
+
for index in range(count):
|
|
342
|
+
raw_name, offset, size_raw = _ENTRY.unpack_from(
|
|
343
|
+
data, HEADER_SIZE + ENTRY_SIZE * index)
|
|
344
|
+
name = raw_name.rstrip(b'\x00').decode('ascii', 'replace')
|
|
345
|
+
compressed = bool(size_raw & _ENTRY_COMPRESSED)
|
|
346
|
+
stored = size_raw & ~_ENTRY_COMPRESSED
|
|
347
|
+
if not name:
|
|
348
|
+
raise SdgccError(f'第 {index} 段缺少名字')
|
|
349
|
+
if name in sections:
|
|
350
|
+
raise SdgccError(f'重复的段名: {name}')
|
|
351
|
+
if offset < table_end or offset + stored > len(data):
|
|
352
|
+
raise SdgccError(f'段 {name} 越界 (offset={offset}, size={stored})')
|
|
353
|
+
chunk = data[offset:offset + stored]
|
|
354
|
+
if compressed:
|
|
355
|
+
if name == SECTION_CODE:
|
|
356
|
+
raise SdgccError('CODE 段不允许压缩 (会破坏 BIN 兼容性)')
|
|
357
|
+
if stored < 4:
|
|
358
|
+
raise SdgccError(f'压缩段 {name} 缺少原始长度')
|
|
359
|
+
try:
|
|
360
|
+
original = zlib.decompress(chunk[4:])
|
|
361
|
+
except zlib.error as e:
|
|
362
|
+
raise SdgccError(f'压缩段 {name} 解压失败: {e}') from e
|
|
363
|
+
expected = struct.unpack_from('<I', chunk, 0)[0]
|
|
364
|
+
if len(original) != expected:
|
|
365
|
+
raise SdgccError(
|
|
366
|
+
f'压缩段 {name} 长度不符: {len(original)} != {expected}')
|
|
367
|
+
sections[name] = original
|
|
368
|
+
entries[name] = (offset, stored, expected, True)
|
|
369
|
+
else:
|
|
370
|
+
sections[name] = chunk
|
|
371
|
+
entries[name] = (offset, stored, stored, False)
|
|
372
|
+
order.append((offset, offset + stored))
|
|
373
|
+
order.sort()
|
|
374
|
+
for (start, end), (next_start, _next_end) in zip(order, order[1:]):
|
|
375
|
+
if next_start < end:
|
|
376
|
+
raise SdgccError('段区间重叠')
|
|
377
|
+
|
|
378
|
+
code = sections.get(SECTION_CODE)
|
|
379
|
+
if code is None:
|
|
380
|
+
raise SdgccError('缺少 CODE 段')
|
|
381
|
+
if len(code) < 6 or code[:5] != Constants.MAGIC_NUMBER:
|
|
382
|
+
raise SdgccError('CODE 段不是 BIN 字节码 (magic 不匹配)')
|
|
383
|
+
|
|
384
|
+
meta = _loads_meta(sections[SECTION_META]) if SECTION_META in sections else {}
|
|
385
|
+
target = raw_target.rstrip(b'\x00').decode('ascii', 'replace') or TARGET_HOST
|
|
386
|
+
if any(item[3] for item in entries.values()):
|
|
387
|
+
flags |= FLAG_COMPRESSED
|
|
388
|
+
container = Sdgcc(version=version, flags=flags, target=target,
|
|
389
|
+
sections=sections, meta=meta, entries=entries)
|
|
390
|
+
# 段表标志与 META 不一致时以段表为准, 但 META 必须能解析 (上面已校验)。
|
|
391
|
+
if not container.multi_file and container.meta.get('sdgcc', {}).get(
|
|
392
|
+
'mode') == MODE_MULTI:
|
|
393
|
+
container.flags |= FLAG_MULTI_FILE
|
|
394
|
+
return container
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def load(path: str) -> Sdgcc:
|
|
398
|
+
with open(path, 'rb') as f:
|
|
399
|
+
return parse(f.read())
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def save(path: str, code: bytes, **kwargs: Any) -> str:
|
|
403
|
+
data = build(code, **kwargs)
|
|
404
|
+
parent = os.path.dirname(os.path.abspath(path))
|
|
405
|
+
if parent:
|
|
406
|
+
os.makedirs(parent, exist_ok=True)
|
|
407
|
+
with open(path, 'wb') as f:
|
|
408
|
+
f.write(data)
|
|
409
|
+
return os.path.abspath(path)
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def unwrap(data: bytes) -> Tuple[bytes, Optional[Sdgcc]]:
|
|
413
|
+
"""取出 BIN 字节流; ``.sdgcc`` 会解包, 旧 ``.bin`` 原样返回。
|
|
414
|
+
|
|
415
|
+
返回 ``(code, container)``, ``container`` 在输入是裸 ``.bin`` 时为 ``None``。
|
|
416
|
+
"""
|
|
417
|
+
if is_sdgcc(data):
|
|
418
|
+
container = parse(data)
|
|
419
|
+
return container.code, container
|
|
420
|
+
return data, None
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def read_code(path: str) -> bytes:
|
|
424
|
+
"""读取 ``.sdgcc`` / ``.bin`` 并返回其中的 BIN v3 字节流。"""
|
|
425
|
+
with open(path, 'rb') as f:
|
|
426
|
+
data = f.read()
|
|
427
|
+
code, _ = unwrap(data)
|
|
428
|
+
return code
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
# ==================== 检查 / 导出工具 ====================
|
|
432
|
+
|
|
433
|
+
_SECTION_FILENAMES = {
|
|
434
|
+
SECTION_CODE: 'program.bin',
|
|
435
|
+
SECTION_META: 'meta.toml',
|
|
436
|
+
SECTION_SYMS: 'symbols.txt',
|
|
437
|
+
SECTION_SRCS: 'sources.txt',
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def describe(container: Sdgcc) -> Dict[str, Any]:
|
|
442
|
+
"""返回便于展示/JSON 输出的容器全量信息。"""
|
|
443
|
+
data = container.to_dict()
|
|
444
|
+
data['flags'] = container.flags
|
|
445
|
+
data['version'] = container.version
|
|
446
|
+
data['sections'] = []
|
|
447
|
+
for name, (offset, stored, logical, compressed) in sorted(
|
|
448
|
+
container.entries.items(),
|
|
449
|
+
key=lambda item: item[1][0]):
|
|
450
|
+
data['sections'].append({
|
|
451
|
+
'name': name,
|
|
452
|
+
'offset': offset,
|
|
453
|
+
'stored': stored,
|
|
454
|
+
'size': logical,
|
|
455
|
+
'compressed': compressed,
|
|
456
|
+
})
|
|
457
|
+
data['meta'] = container.meta
|
|
458
|
+
return data
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def dump(container: Sdgcc, out_dir: str) -> List[str]:
|
|
462
|
+
"""把各段按语义文件名导出到 ``out_dir``, 返回写出的路径。"""
|
|
463
|
+
os.makedirs(out_dir, exist_ok=True)
|
|
464
|
+
written: List[str] = []
|
|
465
|
+
for name in sorted(container.entries,
|
|
466
|
+
key=lambda item: container.entries[item][0]):
|
|
467
|
+
filename = _SECTION_FILENAMES.get(name, name.lower() + '.bin')
|
|
468
|
+
path = os.path.join(out_dir, filename)
|
|
469
|
+
with open(path, 'wb') as f:
|
|
470
|
+
f.write(container.sections[name])
|
|
471
|
+
written.append(os.path.abspath(path))
|
|
472
|
+
return written
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
# ==================== 与 CPU 对接 ====================
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def save_program(cpu: 'Any', path: str, *,
|
|
479
|
+
target: str = TARGET_HOST,
|
|
480
|
+
multi_file: bool = True,
|
|
481
|
+
meta: Optional[Dict[str, Any]] = None,
|
|
482
|
+
symbols: Optional[Iterable[Tuple[int, str]]] = None,
|
|
483
|
+
sources: Optional[Sequence[str]] = None,
|
|
484
|
+
compress: bool = False) -> str:
|
|
485
|
+
"""把已编译的 CPU 状态写成 ``.sdgcc`` (路径以 ``.bin`` 结尾时写裸 BIN)。"""
|
|
486
|
+
from . import crom as crom_mod
|
|
487
|
+
code = crom_mod.dump_bin(cpu)
|
|
488
|
+
if path.lower().endswith('.bin'):
|
|
489
|
+
# 显式要求旧格式: 只写 BIN v3, 便于旧工具/旧版本消费。
|
|
490
|
+
crom_mod.save_bin(cpu, path)
|
|
491
|
+
return os.path.abspath(path)
|
|
492
|
+
return save(path, code, target=target, multi_file=multi_file, meta=meta,
|
|
493
|
+
symbols=symbols, sources=sources, compress=compress)
|