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/object.py
ADDED
|
@@ -0,0 +1,539 @@
|
|
|
1
|
+
"""可重定位 ASM/PL 目标文件与链接器。
|
|
2
|
+
|
|
3
|
+
一个 ``.co`` 对象包含:
|
|
4
|
+
* 未解析标签的操作数 (``('label', name)``);
|
|
5
|
+
* 本地代码标签 / 数据标签;
|
|
6
|
+
* 初始内存段;
|
|
7
|
+
* 入口符号/偏移与内存/SP/Heap 参数。
|
|
8
|
+
|
|
9
|
+
``link_objects`` 负责合并多个对象、给代码/数据分配新基址、解析标签并
|
|
10
|
+
产出可直接交给 AOT/VM 的指令流。``.colib`` 归档由 ``link_inputs`` 按
|
|
11
|
+
未定义符号选择性拉取成员; ``gc_sections=True`` 可删除入口不可达代码。
|
|
12
|
+
ASM/PL 使用未解析标签对象; CIN 无 ``main`` 的源文件也可作为函数库对象
|
|
13
|
+
参与链接。
|
|
14
|
+
|
|
15
|
+
限制: 跨对象符号支持裸标签、``NAME±N`` 简单重定位, 以及 ``DW/DD/DQ label``
|
|
16
|
+
数据段指针重定位; 更复杂的标签算术/多符号表达式仍在对象内解析。
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import base64
|
|
20
|
+
import hashlib
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import struct
|
|
24
|
+
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
|
25
|
+
|
|
26
|
+
from .assembler import Assembler
|
|
27
|
+
from .config import DEFAULT_MEM_SIZE
|
|
28
|
+
from .memory import FastMemory
|
|
29
|
+
|
|
30
|
+
OBJECT_FORMAT = 'codecin-object'
|
|
31
|
+
OBJECT_VERSION = 1
|
|
32
|
+
ARCHIVE_FORMAT = 'codecin-archive'
|
|
33
|
+
ARCHIVE_VERSION = 1
|
|
34
|
+
_STACK_SLOT = 8
|
|
35
|
+
|
|
36
|
+
Instruction = Tuple[str, List[Tuple[Any, ...]]]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ObjectError(Exception):
|
|
40
|
+
"""目标文件格式/链接错误。"""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _decode_arg(arg: Sequence[Any]) -> Tuple[Any, ...]:
|
|
44
|
+
out: List[Any] = []
|
|
45
|
+
for value in arg:
|
|
46
|
+
if isinstance(value, list):
|
|
47
|
+
out.append(tuple(value))
|
|
48
|
+
else:
|
|
49
|
+
out.append(value)
|
|
50
|
+
return tuple(out)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def compile_asm_object(program_file: str,
|
|
54
|
+
mem_size: int = DEFAULT_MEM_SIZE) -> Dict[str, Any]:
|
|
55
|
+
"""把 ASM/PL 源文件编译成可重定位对象 (标签保持未解析)。"""
|
|
56
|
+
mem_size = max(256, int(mem_size))
|
|
57
|
+
memory = FastMemory(mem_size)
|
|
58
|
+
asm = Assembler(memory, preserve_labels=True)
|
|
59
|
+
instructions, labels, data_labels = asm.assemble_file(program_file)
|
|
60
|
+
entry_symbol = 'main' if 'main' in labels else None
|
|
61
|
+
entry_offset = labels.get('main', 0)
|
|
62
|
+
segments = [(addr, bytes(data))
|
|
63
|
+
for addr, data in memory.snapshot_segments()]
|
|
64
|
+
return {
|
|
65
|
+
'format': OBJECT_FORMAT,
|
|
66
|
+
'version': OBJECT_VERSION,
|
|
67
|
+
'kind': 'asm',
|
|
68
|
+
'source': os.path.abspath(program_file),
|
|
69
|
+
'instructions': [(op, [tuple(a) for a in args])
|
|
70
|
+
for op, args in instructions],
|
|
71
|
+
'labels': dict(labels),
|
|
72
|
+
'data_labels': dict(data_labels),
|
|
73
|
+
'data_relocations': [list(r) for r in asm.data_relocations],
|
|
74
|
+
'segments': [[addr, base64.b64encode(data).decode('ascii')]
|
|
75
|
+
for addr, data in segments],
|
|
76
|
+
'entry_symbol': entry_symbol,
|
|
77
|
+
'entry_offset': entry_offset,
|
|
78
|
+
'has_entry': entry_symbol is not None,
|
|
79
|
+
'mem_size': mem_size,
|
|
80
|
+
'sp': mem_size - _STACK_SLOT,
|
|
81
|
+
'heap_base': mem_size // 2,
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def compile_cin_object(program_file: str,
|
|
86
|
+
mem_size: int = DEFAULT_MEM_SIZE) -> Dict[str, Any]:
|
|
87
|
+
"""把 CIN 源文件编译成对象;无 main 的文件作为函数库对象。
|
|
88
|
+
|
|
89
|
+
数据地址 (字符串/标量全局/struct 指针槽) 以对象内前缀符号 + 重定位保存,
|
|
90
|
+
链接时按数据基址重写。无 main 的库对象会自动去掉 ``CALL main; HALT``
|
|
91
|
+
入口桩。
|
|
92
|
+
"""
|
|
93
|
+
from .cin import CINCompiler
|
|
94
|
+
|
|
95
|
+
mem_size = max(256, int(mem_size))
|
|
96
|
+
try:
|
|
97
|
+
res = CINCompiler().compile(program_file, relocatable=True)
|
|
98
|
+
except Exception as e: # noqa: BLE001
|
|
99
|
+
raise ObjectError(f'CIN 编译失败: {e}') from e
|
|
100
|
+
instructions = list(res.instructions)
|
|
101
|
+
labels = dict(res.labels)
|
|
102
|
+
data_labels = dict(res.data_labels)
|
|
103
|
+
# CIN 数据标签是对象内局部符号 (str_0 等), 必须加对象前缀避免多对象冲突。
|
|
104
|
+
prefix = ('__cin_' + hashlib.sha1(
|
|
105
|
+
os.path.abspath(program_file).encode()).hexdigest()[:10] + '__')
|
|
106
|
+
renames = {name: prefix + name for name in data_labels
|
|
107
|
+
if not name.startswith('global_')}
|
|
108
|
+
if renames:
|
|
109
|
+
data_labels = {renames.get(name, name): addr
|
|
110
|
+
for name, addr in data_labels.items()}
|
|
111
|
+
rewritten = []
|
|
112
|
+
for op, args in instructions:
|
|
113
|
+
new_args = []
|
|
114
|
+
for arg in args:
|
|
115
|
+
if arg and arg[0] in ('reloc', 'label') \
|
|
116
|
+
and arg[1] in renames:
|
|
117
|
+
if arg[0] == 'reloc':
|
|
118
|
+
new_args.append(('reloc', renames[arg[1]], arg[2]))
|
|
119
|
+
else:
|
|
120
|
+
new_args.append(('label', renames[arg[1]]))
|
|
121
|
+
else:
|
|
122
|
+
new_args.append(arg)
|
|
123
|
+
rewritten.append((op, new_args))
|
|
124
|
+
instructions = rewritten
|
|
125
|
+
data_relocations = [
|
|
126
|
+
(addr, width, renames.get(name, name), addend)
|
|
127
|
+
for addr, width, name, addend in res.data_relocations
|
|
128
|
+
]
|
|
129
|
+
has_main = 'main' in labels
|
|
130
|
+
if not has_main:
|
|
131
|
+
remove = None
|
|
132
|
+
for i, (op, args) in enumerate(instructions):
|
|
133
|
+
if (op == 'CALL' and args and args[0][0] == 'label'
|
|
134
|
+
and args[0][1] == 'main'):
|
|
135
|
+
remove = i
|
|
136
|
+
break
|
|
137
|
+
if remove is not None:
|
|
138
|
+
end = remove + 1
|
|
139
|
+
if (end < len(instructions)
|
|
140
|
+
and instructions[end][0] == 'HALT'):
|
|
141
|
+
end += 1
|
|
142
|
+
del instructions[remove:end]
|
|
143
|
+
shift = end - remove
|
|
144
|
+
labels = {name: (idx - shift if idx >= end else idx)
|
|
145
|
+
for name, idx in labels.items()}
|
|
146
|
+
segs: List[Tuple[int, bytes]] = []
|
|
147
|
+
if res.data_writes:
|
|
148
|
+
end_max = max(addr + len(data) for addr, data in res.data_writes)
|
|
149
|
+
buf = bytearray(end_max)
|
|
150
|
+
for addr, data in res.data_writes:
|
|
151
|
+
buf[addr:addr + len(data)] = data
|
|
152
|
+
segs.append((0, bytes(buf)))
|
|
153
|
+
return {
|
|
154
|
+
'format': OBJECT_FORMAT,
|
|
155
|
+
'version': OBJECT_VERSION,
|
|
156
|
+
'kind': 'cin',
|
|
157
|
+
'source': os.path.abspath(program_file),
|
|
158
|
+
'instructions': [(op, [tuple(a) for a in args])
|
|
159
|
+
for op, args in instructions],
|
|
160
|
+
'labels': labels,
|
|
161
|
+
'data_labels': data_labels,
|
|
162
|
+
'data_relocations': [list(r) for r in data_relocations],
|
|
163
|
+
'segments': [[addr, base64.b64encode(data).decode('ascii')]
|
|
164
|
+
for addr, data in segs],
|
|
165
|
+
'entry_symbol': None,
|
|
166
|
+
'entry_offset': 0,
|
|
167
|
+
'has_entry': has_main,
|
|
168
|
+
'mem_size': mem_size,
|
|
169
|
+
'sp': mem_size - _STACK_SLOT,
|
|
170
|
+
'heap_base': mem_size // 2,
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def write_object(obj: Dict[str, Any], path: str) -> str:
|
|
175
|
+
with open(path, 'w', encoding='utf-8', newline='\n') as f:
|
|
176
|
+
json.dump(obj, f, ensure_ascii=False, separators=(',', ':'))
|
|
177
|
+
f.write('\n')
|
|
178
|
+
return os.path.abspath(path)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def read_object(path: str) -> Dict[str, Any]:
|
|
182
|
+
try:
|
|
183
|
+
with open(path, encoding='utf-8') as f:
|
|
184
|
+
obj = json.load(f)
|
|
185
|
+
except (OSError, ValueError) as e:
|
|
186
|
+
raise ObjectError(f'无法读取对象文件 {path}: {e}') from e
|
|
187
|
+
if not isinstance(obj, dict) or obj.get('format') != OBJECT_FORMAT:
|
|
188
|
+
raise ObjectError(f'不是 Code CIN 对象文件: {path}')
|
|
189
|
+
if obj.get('version') != OBJECT_VERSION:
|
|
190
|
+
raise ObjectError(f'不支持的对象版本: {obj.get("version")}')
|
|
191
|
+
obj['instructions'] = [
|
|
192
|
+
(op, [_decode_arg(a) for a in args])
|
|
193
|
+
for op, args in obj.get('instructions', [])
|
|
194
|
+
]
|
|
195
|
+
obj['segments'] = [
|
|
196
|
+
(int(addr), base64.b64decode(data))
|
|
197
|
+
for addr, data in obj.get('segments', [])
|
|
198
|
+
]
|
|
199
|
+
return obj
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _align(value: int, align: int = 16) -> int:
|
|
203
|
+
return (value + align - 1) // align * align
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
_CONTROL_BRANCH = {'B'}
|
|
207
|
+
_CONTROL_JUMP = {'JMP'}
|
|
208
|
+
_CONTROL_CALL = {'CALL', 'JAL'}
|
|
209
|
+
_CONTROL_STOP = {'RET', 'HALT'}
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _control_target(op: str, args: Sequence[Tuple[Any, ...]]):
|
|
213
|
+
if op in _CONTROL_BRANCH | _CONTROL_JUMP | _CONTROL_CALL:
|
|
214
|
+
for arg in args:
|
|
215
|
+
if arg and arg[0] == 'imm':
|
|
216
|
+
return int(arg[1])
|
|
217
|
+
return None
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def gc_instructions(instructions: Sequence[Instruction],
|
|
221
|
+
labels: Dict[str, int],
|
|
222
|
+
entry_pc: int) -> Optional[Tuple[List[Instruction],
|
|
223
|
+
Dict[str, int], int]]:
|
|
224
|
+
"""保守的链接期代码段 GC: 从入口沿控制流删除不可达函数/桩。
|
|
225
|
+
|
|
226
|
+
只要遇到动态控制流 (CALL/JMP 寄存器) 就放弃 GC 返回 None, 避免误删。
|
|
227
|
+
数据指针指向代码的情况由调用方先行禁用 GC。
|
|
228
|
+
"""
|
|
229
|
+
n = len(instructions)
|
|
230
|
+
if n == 0:
|
|
231
|
+
return None
|
|
232
|
+
entry = int(entry_pc)
|
|
233
|
+
if not (0 <= entry < n):
|
|
234
|
+
return None
|
|
235
|
+
|
|
236
|
+
reachable = set()
|
|
237
|
+
stack = [entry]
|
|
238
|
+
while stack:
|
|
239
|
+
idx = stack.pop()
|
|
240
|
+
if idx < 0 or idx >= n or idx in reachable:
|
|
241
|
+
continue
|
|
242
|
+
reachable.add(idx)
|
|
243
|
+
op, args = instructions[idx]
|
|
244
|
+
if op in _CONTROL_STOP:
|
|
245
|
+
continue
|
|
246
|
+
if op in _CONTROL_JUMP | _CONTROL_BRANCH:
|
|
247
|
+
target = _control_target(op, args)
|
|
248
|
+
if target is None:
|
|
249
|
+
return None
|
|
250
|
+
stack.append(target)
|
|
251
|
+
conditional = any(a and a[0] == 'cond' for a in args)
|
|
252
|
+
if op in _CONTROL_BRANCH and not conditional:
|
|
253
|
+
continue # 无条件 B
|
|
254
|
+
stack.append(idx + 1)
|
|
255
|
+
continue
|
|
256
|
+
if op in _CONTROL_CALL:
|
|
257
|
+
target = _control_target(op, args)
|
|
258
|
+
if target is None:
|
|
259
|
+
return None
|
|
260
|
+
stack.append(target)
|
|
261
|
+
stack.append(idx + 1)
|
|
262
|
+
continue
|
|
263
|
+
if op in ('BR', 'JR', 'BRANCH'):
|
|
264
|
+
return None
|
|
265
|
+
stack.append(idx + 1)
|
|
266
|
+
|
|
267
|
+
old_to_new = {}
|
|
268
|
+
new_ins: List[Instruction] = []
|
|
269
|
+
for old in sorted(reachable):
|
|
270
|
+
old_to_new[old] = len(new_ins)
|
|
271
|
+
new_ins.append(instructions[old])
|
|
272
|
+
|
|
273
|
+
def remap(idx: int) -> int:
|
|
274
|
+
if idx not in old_to_new:
|
|
275
|
+
raise ObjectError(f'GC 后仍引用不可达指令: {idx}')
|
|
276
|
+
return old_to_new[idx]
|
|
277
|
+
|
|
278
|
+
for i, (op, args) in enumerate(new_ins):
|
|
279
|
+
if op not in _CONTROL_JUMP | _CONTROL_BRANCH | _CONTROL_CALL:
|
|
280
|
+
continue
|
|
281
|
+
new_args = []
|
|
282
|
+
for arg in args:
|
|
283
|
+
if arg and arg[0] == 'imm':
|
|
284
|
+
new_args.append(('imm', remap(int(arg[1]))))
|
|
285
|
+
else:
|
|
286
|
+
new_args.append(arg)
|
|
287
|
+
new_ins[i] = (op, new_args)
|
|
288
|
+
|
|
289
|
+
new_labels = {name: remap(idx) for name, idx in labels.items()
|
|
290
|
+
if idx in reachable}
|
|
291
|
+
return new_ins, new_labels, remap(entry)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def link_objects(objects: Sequence[Dict[str, Any]],
|
|
295
|
+
gc_sections: bool = False) -> Dict[str, Any]:
|
|
296
|
+
"""合并多个可重定位对象, 返回解析后的程序描述。"""
|
|
297
|
+
if not objects:
|
|
298
|
+
raise ObjectError('没有输入对象')
|
|
299
|
+
|
|
300
|
+
# 入口对象放到最前: CIN 主对象的数据地址是编译期绝对值, 数据基址必须为 0。
|
|
301
|
+
entry_objs = [o for o in objects
|
|
302
|
+
if o.get('has_entry') or o.get('entry_symbol')]
|
|
303
|
+
if len(entry_objs) > 1:
|
|
304
|
+
raise ObjectError('多个对象都定义了入口')
|
|
305
|
+
if entry_objs:
|
|
306
|
+
first = entry_objs[0]
|
|
307
|
+
objects = [first] + [o for o in objects if o is not first]
|
|
308
|
+
|
|
309
|
+
code_base = 0
|
|
310
|
+
data_cursor = 0
|
|
311
|
+
code_labels: Dict[str, int] = {}
|
|
312
|
+
data_labels: Dict[str, int] = {}
|
|
313
|
+
segments: List[Tuple[int, bytes]] = []
|
|
314
|
+
placements: List[Tuple[Dict[str, Any], int, int]] = []
|
|
315
|
+
|
|
316
|
+
for obj in objects:
|
|
317
|
+
if obj.get('format') != OBJECT_FORMAT:
|
|
318
|
+
raise ObjectError('输入不是 Code CIN 对象')
|
|
319
|
+
data_base = _align(data_cursor)
|
|
320
|
+
placements.append((obj, code_base, data_base))
|
|
321
|
+
for name, idx in obj.get('labels', {}).items():
|
|
322
|
+
if name in code_labels or name in data_labels:
|
|
323
|
+
raise ObjectError(f'重复符号: {name}')
|
|
324
|
+
code_labels[name] = code_base + int(idx)
|
|
325
|
+
for name, off in obj.get('data_labels', {}).items():
|
|
326
|
+
if name in code_labels or name in data_labels:
|
|
327
|
+
raise ObjectError(f'重复符号: {name}')
|
|
328
|
+
data_labels[name] = data_base + int(off)
|
|
329
|
+
for addr, data in obj.get('segments', []):
|
|
330
|
+
if isinstance(data, str):
|
|
331
|
+
data = base64.b64decode(data)
|
|
332
|
+
segments.append((data_base + int(addr), bytes(data)))
|
|
333
|
+
data_cursor = max(data_cursor, data_base + int(addr) + len(data))
|
|
334
|
+
code_base += len(obj.get('instructions', []))
|
|
335
|
+
|
|
336
|
+
# 数据段重定位: DQ/DD/DW label 等。合并成连续数据缓冲后按符号写回。
|
|
337
|
+
if data_cursor:
|
|
338
|
+
data_buf = bytearray(data_cursor)
|
|
339
|
+
for addr, data in segments:
|
|
340
|
+
data_buf[addr:addr + len(data)] = data
|
|
341
|
+
for obj, _code_base, data_base in placements:
|
|
342
|
+
for off, width, name, addend in obj.get('data_relocations', []):
|
|
343
|
+
if name in code_labels:
|
|
344
|
+
value = code_labels[name] + int(addend)
|
|
345
|
+
elif name in data_labels:
|
|
346
|
+
value = data_labels[name] + int(addend)
|
|
347
|
+
else:
|
|
348
|
+
raise ObjectError(f'未定义符号: {name}')
|
|
349
|
+
w = int(width)
|
|
350
|
+
at = data_base + int(off)
|
|
351
|
+
if w == 2:
|
|
352
|
+
struct.pack_into('<H', data_buf, at, value & 0xFFFF)
|
|
353
|
+
elif w == 4:
|
|
354
|
+
struct.pack_into('<I', data_buf, at, value & 0xFFFFFFFF)
|
|
355
|
+
elif w == 8:
|
|
356
|
+
struct.pack_into('<Q', data_buf, at,
|
|
357
|
+
value & 0xFFFFFFFFFFFFFFFF)
|
|
358
|
+
else:
|
|
359
|
+
raise ObjectError(f'不支持的数据重定位宽度: {w}')
|
|
360
|
+
segments = [(0, bytes(data_buf))]
|
|
361
|
+
|
|
362
|
+
# 入口: 恰好一个对象带入口; ASM 用 main 符号, CIN 用入口桩偏移。
|
|
363
|
+
entries = [p for p in placements
|
|
364
|
+
if p[0].get('has_entry') or p[0].get('entry_symbol')]
|
|
365
|
+
if len(entries) > 1:
|
|
366
|
+
raise ObjectError('多个对象都定义了入口')
|
|
367
|
+
if entries:
|
|
368
|
+
obj, base, _data_base = entries[0]
|
|
369
|
+
symbol = obj.get('entry_symbol')
|
|
370
|
+
if symbol:
|
|
371
|
+
if symbol not in code_labels:
|
|
372
|
+
raise ObjectError(f'入口符号未定义: {symbol}')
|
|
373
|
+
entry_pc = code_labels[symbol]
|
|
374
|
+
else:
|
|
375
|
+
entry_pc = base + int(obj.get('entry_offset', 0))
|
|
376
|
+
else:
|
|
377
|
+
obj, base, _data_base = placements[0]
|
|
378
|
+
entry_pc = base + int(obj.get('entry_offset', 0))
|
|
379
|
+
|
|
380
|
+
instructions: List[Instruction] = []
|
|
381
|
+
for obj, _code_base, _data_base in placements:
|
|
382
|
+
for op, args in obj.get('instructions', []):
|
|
383
|
+
new_args = []
|
|
384
|
+
for arg in args:
|
|
385
|
+
if arg and arg[0] in ('label', 'reloc'):
|
|
386
|
+
name = arg[1]
|
|
387
|
+
addend = int(arg[2]) if arg[0] == 'reloc' else 0
|
|
388
|
+
if name in code_labels:
|
|
389
|
+
new_args.append(('imm', code_labels[name] + addend))
|
|
390
|
+
elif name in data_labels:
|
|
391
|
+
new_args.append(('imm', data_labels[name] + addend))
|
|
392
|
+
else:
|
|
393
|
+
raise ObjectError(f'未定义符号: {name}')
|
|
394
|
+
else:
|
|
395
|
+
new_args.append(tuple(arg))
|
|
396
|
+
instructions.append((op, new_args))
|
|
397
|
+
|
|
398
|
+
# 数据里保存了代码地址时不做 GC, 否则重排指令会让函数指针失效。
|
|
399
|
+
has_code_pointer = False
|
|
400
|
+
for obj, _b, _d in placements:
|
|
401
|
+
for _off, _w, name, _add in obj.get('data_relocations', []):
|
|
402
|
+
if name in code_labels:
|
|
403
|
+
has_code_pointer = True
|
|
404
|
+
break
|
|
405
|
+
if gc_sections and not has_code_pointer:
|
|
406
|
+
gc_res = gc_instructions(instructions, code_labels, entry_pc)
|
|
407
|
+
if gc_res is not None:
|
|
408
|
+
instructions, code_labels, entry_pc = gc_res
|
|
409
|
+
|
|
410
|
+
mem_size = max(int(obj.get('mem_size', DEFAULT_MEM_SIZE))
|
|
411
|
+
for obj, _b, _d in placements)
|
|
412
|
+
return {
|
|
413
|
+
'format': OBJECT_FORMAT,
|
|
414
|
+
'version': OBJECT_VERSION,
|
|
415
|
+
'source': '<linked>',
|
|
416
|
+
'instructions': instructions,
|
|
417
|
+
'labels': code_labels,
|
|
418
|
+
'data_labels': data_labels,
|
|
419
|
+
'segments': segments,
|
|
420
|
+
'entry_pc': entry_pc,
|
|
421
|
+
'mem_size': mem_size,
|
|
422
|
+
'sp': mem_size - _STACK_SLOT,
|
|
423
|
+
'heap_base': mem_size // 2,
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def create_archive(objects: Sequence[Dict[str, Any]]) -> Dict[str, Any]:
|
|
428
|
+
return {
|
|
429
|
+
'format': ARCHIVE_FORMAT,
|
|
430
|
+
'version': ARCHIVE_VERSION,
|
|
431
|
+
'members': list(objects),
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def write_archive(objects: Sequence[Dict[str, Any]], path: str) -> str:
|
|
436
|
+
with open(path, 'w', encoding='utf-8', newline='\n') as f:
|
|
437
|
+
json.dump(create_archive(objects), f, ensure_ascii=False,
|
|
438
|
+
separators=(',', ':'))
|
|
439
|
+
f.write('\n')
|
|
440
|
+
return os.path.abspath(path)
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def read_archive(path: str) -> List[Dict[str, Any]]:
|
|
444
|
+
try:
|
|
445
|
+
with open(path, encoding='utf-8') as f:
|
|
446
|
+
data = json.load(f)
|
|
447
|
+
except (OSError, ValueError) as e:
|
|
448
|
+
raise ObjectError(f'无法读取归档文件 {path}: {e}') from e
|
|
449
|
+
if not isinstance(data, dict) or data.get('format') != ARCHIVE_FORMAT:
|
|
450
|
+
raise ObjectError(f'不是 Code CIN 归档文件: {path}')
|
|
451
|
+
if data.get('version') != ARCHIVE_VERSION:
|
|
452
|
+
raise ObjectError(f'不支持的归档版本: {data.get("version")}')
|
|
453
|
+
members = data.get('members')
|
|
454
|
+
if not isinstance(members, list):
|
|
455
|
+
raise ObjectError(f'归档成员非法: {path}')
|
|
456
|
+
return members
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _defined_symbols(obj: Dict[str, Any]) -> set:
|
|
460
|
+
return set(obj.get('labels', {})) | set(obj.get('data_labels', {}))
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _referenced_symbols(obj: Dict[str, Any]) -> set:
|
|
464
|
+
refs = set()
|
|
465
|
+
for _op, args in obj.get('instructions', []):
|
|
466
|
+
for arg in args:
|
|
467
|
+
if arg and arg[0] in ('label', 'reloc'):
|
|
468
|
+
refs.add(arg[1])
|
|
469
|
+
for _addr, _width, name, _add in obj.get('data_relocations', []):
|
|
470
|
+
refs.add(name)
|
|
471
|
+
return refs
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def _select_archive_members(explicit: List[Dict[str, Any]],
|
|
475
|
+
archives: List[List[Dict[str, Any]]]
|
|
476
|
+
) -> List[Dict[str, Any]]:
|
|
477
|
+
"""C 风格静态库语义: 只拉取能解决当前未定义符号的成员。"""
|
|
478
|
+
selected = list(explicit)
|
|
479
|
+
defined = set()
|
|
480
|
+
for obj in selected:
|
|
481
|
+
defined |= _defined_symbols(obj)
|
|
482
|
+
unresolved = set()
|
|
483
|
+
for obj in selected:
|
|
484
|
+
unresolved |= _referenced_symbols(obj)
|
|
485
|
+
unresolved -= defined
|
|
486
|
+
|
|
487
|
+
changed = True
|
|
488
|
+
while changed:
|
|
489
|
+
changed = False
|
|
490
|
+
for members in archives:
|
|
491
|
+
for obj in members:
|
|
492
|
+
if obj in selected:
|
|
493
|
+
continue
|
|
494
|
+
gained = _defined_symbols(obj) & unresolved
|
|
495
|
+
if not gained:
|
|
496
|
+
continue
|
|
497
|
+
selected.append(obj)
|
|
498
|
+
defined |= _defined_symbols(obj)
|
|
499
|
+
unresolved |= _referenced_symbols(obj)
|
|
500
|
+
unresolved -= defined
|
|
501
|
+
changed = True
|
|
502
|
+
if unresolved:
|
|
503
|
+
raise ObjectError('未定义符号: ' + ', '.join(sorted(unresolved)[:8]))
|
|
504
|
+
return selected
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def read_input_object(path: str) -> Dict[str, Any]:
|
|
508
|
+
"""链接输入: 对象文件或 CIN/ASM/PL 源文件 (源文件即时编译为对象)。"""
|
|
509
|
+
ext = os.path.splitext(path)[1].lower()
|
|
510
|
+
if ext == '.cin':
|
|
511
|
+
return compile_cin_object(path)
|
|
512
|
+
if ext in ('.asm', '.pl'):
|
|
513
|
+
return compile_asm_object(path)
|
|
514
|
+
return read_object(path)
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def link_inputs(paths: Sequence[str],
|
|
518
|
+
gc_sections: bool = False) -> Dict[str, Any]:
|
|
519
|
+
"""链接对象、源文件与 ``.colib`` 静态库归档。"""
|
|
520
|
+
explicit: List[Dict[str, Any]] = []
|
|
521
|
+
archives: List[List[Dict[str, Any]]] = []
|
|
522
|
+
for path in paths:
|
|
523
|
+
ext = os.path.splitext(path)[1].lower()
|
|
524
|
+
if ext in ('.cin', '.asm', '.pl'):
|
|
525
|
+
explicit.append(read_input_object(path))
|
|
526
|
+
continue
|
|
527
|
+
try:
|
|
528
|
+
explicit.append(read_object(path))
|
|
529
|
+
continue
|
|
530
|
+
except ObjectError:
|
|
531
|
+
pass
|
|
532
|
+
archives.append(read_archive(path))
|
|
533
|
+
return link_objects(_select_archive_members(explicit, archives),
|
|
534
|
+
gc_sections=gc_sections)
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def link_files(paths: Sequence[str],
|
|
538
|
+
gc_sections: bool = False) -> Dict[str, Any]:
|
|
539
|
+
return link_inputs(paths, gc_sections=gc_sections)
|