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/optimizer.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"""CIN/ASM 指令流优化器 (--optimize 0..3)。
|
|
2
|
+
|
|
3
|
+
优化发生在 UCBC 编码之前,只改 ``(opcode, operands)`` 列表与代码标签,
|
|
4
|
+
不触碰数据段。所有 pass 都以“语义等价”为前提:
|
|
5
|
+
|
|
6
|
+
* 被任何代码标签指向的指令永不被删除 (保护分支/函数入口/循环头);
|
|
7
|
+
* 只删除无副作用的整数/移动指令;SYS、内存、浮点/向量、栈操作一律保守;
|
|
8
|
+
* 删除后重新映射标签和入口索引。
|
|
9
|
+
|
|
10
|
+
级别:
|
|
11
|
+
-O0 不做任何优化
|
|
12
|
+
-O1 去掉 NOP / MOV rd,rd / 跳到下一条的 JMP
|
|
13
|
+
-O2 + 常量折叠 (MOV imm + 整数立即数运算)
|
|
14
|
+
-O3 + 无条件跳转后的不可达代码删除
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from typing import Dict, Iterable, List, Optional, Sequence, Set, Tuple
|
|
18
|
+
|
|
19
|
+
Instruction = Tuple[str, List[Tuple[object, ...]]]
|
|
20
|
+
|
|
21
|
+
#: 不改变标志位、可安全折叠的二元立即数指令。
|
|
22
|
+
_FOLD_BIN = {'ADD', 'SUB', 'MUL', 'AND', 'OR', 'XOR', 'SHL', 'SHR'}
|
|
23
|
+
_FOLD_BIN_I = {'ADDI', 'XORI', 'ORI', 'ANDI', 'LSL', 'LSR', 'ASR'}
|
|
24
|
+
_TERMINATORS = {'JMP', 'HALT', 'RET', 'BR', 'JAL', 'JALR'}
|
|
25
|
+
|
|
26
|
+
_MASK64 = 0xFFFFFFFFFFFFFFFF
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _reg(arg: Tuple[object, ...]) -> Optional[int]:
|
|
30
|
+
return int(arg[1]) if arg and arg[0] == 'reg' else None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _imm(arg: Tuple[object, ...]) -> Optional[int]:
|
|
34
|
+
return int(arg[1]) & _MASK64 if arg and arg[0] == 'imm' else None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _target(arg: Tuple[object, ...], labels: Dict[str, int]) -> Optional[int]:
|
|
38
|
+
if arg and arg[0] == 'label':
|
|
39
|
+
return labels.get(str(arg[1]))
|
|
40
|
+
if arg and arg[0] == 'imm':
|
|
41
|
+
return int(arg[1])
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _i64(v: int) -> int:
|
|
46
|
+
v &= _MASK64
|
|
47
|
+
return v - (1 << 64) if v >= (1 << 63) else v
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _fold(op: str, a: int, b: int) -> Optional[int]:
|
|
51
|
+
"""折叠整数运算;除零/未知操作返回 None。"""
|
|
52
|
+
if op in ('ADD', 'ADDI'):
|
|
53
|
+
return (a + b) & _MASK64
|
|
54
|
+
if op == 'SUB':
|
|
55
|
+
return (a - b) & _MASK64
|
|
56
|
+
if op == 'MUL':
|
|
57
|
+
return (a * b) & _MASK64
|
|
58
|
+
if op == 'AND':
|
|
59
|
+
return a & b
|
|
60
|
+
if op == 'OR':
|
|
61
|
+
return a | b
|
|
62
|
+
if op in ('XOR', 'XORI'):
|
|
63
|
+
return a ^ b
|
|
64
|
+
if op == 'ORI':
|
|
65
|
+
return a | b
|
|
66
|
+
if op == 'ANDI':
|
|
67
|
+
return a & b
|
|
68
|
+
if op in ('SHL', 'LSL'):
|
|
69
|
+
return (a << (b & 63)) & _MASK64
|
|
70
|
+
if op in ('SHR', 'LSR'):
|
|
71
|
+
return (a & _MASK64) >> (b & 63)
|
|
72
|
+
if op == 'ASR':
|
|
73
|
+
return (_i64(a) >> (b & 63)) & _MASK64
|
|
74
|
+
return None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _protected(labels: Dict[str, int], entry_pc: int,
|
|
78
|
+
extra: Iterable[int]) -> Set[int]:
|
|
79
|
+
out = {int(v) for v in labels.values() if int(v) >= 0}
|
|
80
|
+
if entry_pc >= 0:
|
|
81
|
+
out.add(int(entry_pc))
|
|
82
|
+
out.update(int(x) for x in extra if int(x) >= 0)
|
|
83
|
+
return out
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _remap(instructions: Sequence[Instruction],
|
|
87
|
+
labels: Dict[str, int],
|
|
88
|
+
entry_pc: int) -> Tuple[List[Instruction], Dict[str, int], int]:
|
|
89
|
+
"""删除已被标记为 None 的指令并重映射标签/入口。"""
|
|
90
|
+
mapping: Dict[int, int] = {}
|
|
91
|
+
kept: List[Instruction] = []
|
|
92
|
+
for old, ins in enumerate(instructions):
|
|
93
|
+
if ins is None: # type: ignore[comparison-overlap]
|
|
94
|
+
continue
|
|
95
|
+
mapping[old] = len(kept)
|
|
96
|
+
kept.append(ins)
|
|
97
|
+
if not kept:
|
|
98
|
+
return [], {}, 0
|
|
99
|
+
new_labels: Dict[str, int] = {}
|
|
100
|
+
for name, old in labels.items():
|
|
101
|
+
new_labels[name] = mapping.get(int(old), len(kept))
|
|
102
|
+
new_entry = mapping.get(int(entry_pc), 0)
|
|
103
|
+
return kept, new_labels, new_entry
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _o1(instructions: List[Optional[Instruction]],
|
|
107
|
+
labels: Dict[str, int],
|
|
108
|
+
protected: Set[int]) -> None:
|
|
109
|
+
for i, ins in enumerate(instructions):
|
|
110
|
+
if ins is None or i in protected:
|
|
111
|
+
continue
|
|
112
|
+
op, args = ins
|
|
113
|
+
if op == 'NOP':
|
|
114
|
+
instructions[i] = None
|
|
115
|
+
continue
|
|
116
|
+
if op == 'MOV' and len(args) >= 2:
|
|
117
|
+
rd, rs = _reg(args[0]), _reg(args[1])
|
|
118
|
+
if rd is not None and rs is not None and rd == rs:
|
|
119
|
+
instructions[i] = None
|
|
120
|
+
continue
|
|
121
|
+
if op == 'ADDI' and len(args) >= 3:
|
|
122
|
+
rd, rs = _reg(args[0]), _reg(args[1])
|
|
123
|
+
imm = _imm(args[2])
|
|
124
|
+
if rd is not None and rs is not None and rd == rs and imm == 0:
|
|
125
|
+
instructions[i] = ('MOV', [('reg', rd), ('reg', rs)])
|
|
126
|
+
continue
|
|
127
|
+
if op == 'JMP' and len(args) >= 1:
|
|
128
|
+
target = _target(args[0], labels)
|
|
129
|
+
if target == i + 1:
|
|
130
|
+
instructions[i] = None
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _o2(instructions: List[Optional[Instruction]],
|
|
134
|
+
labels: Dict[str, int],
|
|
135
|
+
protected: Set[int]) -> None:
|
|
136
|
+
# MOV rd, imm + 立即数运算 -> MOV rd, folded
|
|
137
|
+
for i in range(len(instructions) - 1):
|
|
138
|
+
first = instructions[i]
|
|
139
|
+
second = instructions[i + 1]
|
|
140
|
+
if first is None or second is None or (i + 1) in protected:
|
|
141
|
+
continue
|
|
142
|
+
op1, args1 = first
|
|
143
|
+
if op1 != 'MOV' or len(args1) < 2:
|
|
144
|
+
continue
|
|
145
|
+
rd = _reg(args1[0])
|
|
146
|
+
imm = _imm(args1[1])
|
|
147
|
+
if rd is None or imm is None:
|
|
148
|
+
continue
|
|
149
|
+
op2, args2 = second
|
|
150
|
+
if op2 in _FOLD_BIN and len(args2) >= 2:
|
|
151
|
+
# Base 二元形式: ADD rd, imm 的源就是 rd; 右侧是寄存器时无法折叠。
|
|
152
|
+
if _reg(args2[0]) != rd:
|
|
153
|
+
continue
|
|
154
|
+
rhs = _imm(args2[1])
|
|
155
|
+
if rhs is None:
|
|
156
|
+
continue
|
|
157
|
+
folded = _fold(op2, imm, rhs)
|
|
158
|
+
if folded is None:
|
|
159
|
+
continue
|
|
160
|
+
instructions[i] = ('MOV', [('reg', rd), ('imm', folded)])
|
|
161
|
+
instructions[i + 1] = None
|
|
162
|
+
continue
|
|
163
|
+
if op2 in _FOLD_BIN_I and len(args2) >= 3:
|
|
164
|
+
rd2, rs2 = _reg(args2[0]), _reg(args2[1])
|
|
165
|
+
rhs = _imm(args2[2])
|
|
166
|
+
if rd2 is None or rs2 != rd or rhs is None:
|
|
167
|
+
continue
|
|
168
|
+
folded = _fold(op2, imm, rhs)
|
|
169
|
+
if folded is None:
|
|
170
|
+
continue
|
|
171
|
+
# 源寄存器已知; 目标寄存器可以不同 (ADDI rd, rs, imm)。
|
|
172
|
+
instructions[i + 1] = ('MOV', [('reg', rd2), ('imm', folded)])
|
|
173
|
+
if rd2 == rd and i not in protected:
|
|
174
|
+
instructions[i] = None
|
|
175
|
+
continue
|
|
176
|
+
if op2 == 'MOV' and len(args2) >= 2:
|
|
177
|
+
# MOV rd, imm; MOV rd, imm -> 前者可删 (后者覆盖, 且非标签目标)
|
|
178
|
+
rd2 = _reg(args2[0])
|
|
179
|
+
if rd2 == rd and i not in protected:
|
|
180
|
+
instructions[i] = None
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _o3(instructions: List[Optional[Instruction]],
|
|
184
|
+
labels: Dict[str, int],
|
|
185
|
+
protected: Set[int]) -> None:
|
|
186
|
+
unreachable = False
|
|
187
|
+
for i, ins in enumerate(instructions):
|
|
188
|
+
if ins is None:
|
|
189
|
+
continue
|
|
190
|
+
if i in protected:
|
|
191
|
+
unreachable = False
|
|
192
|
+
if unreachable:
|
|
193
|
+
instructions[i] = None
|
|
194
|
+
continue
|
|
195
|
+
op, args = ins
|
|
196
|
+
if op == 'HALT' or op == 'RET':
|
|
197
|
+
unreachable = True
|
|
198
|
+
elif op == 'JMP' and len(args) >= 1:
|
|
199
|
+
target = _target(args[0], labels)
|
|
200
|
+
# 跳到下一条时后续代码仍可达; 其余跳转后到下一条标签之间不可达。
|
|
201
|
+
if target is not None and target != i + 1:
|
|
202
|
+
unreachable = True
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def optimize(instructions: Sequence[Instruction],
|
|
206
|
+
labels: Dict[str, int],
|
|
207
|
+
level: int = 0,
|
|
208
|
+
entry_pc: int = 0,
|
|
209
|
+
protected_extra: Iterable[int] = ()) -> Tuple[List[Instruction],
|
|
210
|
+
Dict[str, int],
|
|
211
|
+
int]:
|
|
212
|
+
"""按级别优化指令流,返回 ``(instructions, labels, entry_pc)``。
|
|
213
|
+
|
|
214
|
+
level <= 0 时原样返回 (不做复制以外的改动)。标签会重新映射到新下标。
|
|
215
|
+
"""
|
|
216
|
+
level = max(0, min(3, int(level)))
|
|
217
|
+
if level == 0 or not instructions:
|
|
218
|
+
return list(instructions), dict(labels), int(entry_pc)
|
|
219
|
+
|
|
220
|
+
protected = _protected(labels, entry_pc, protected_extra)
|
|
221
|
+
# CALL/JAL 的返回地址是隐式标签; 不保护的话, 删除恰好位于返回点的
|
|
222
|
+
# 指令会让 RET 落到错误位置。
|
|
223
|
+
protected.update(
|
|
224
|
+
i + 1 for i, (op, _args) in enumerate(instructions)
|
|
225
|
+
if op in ('CALL', 'BL', 'JAL') and i + 1 < len(instructions))
|
|
226
|
+
work: List[Optional[Instruction]] = list(instructions)
|
|
227
|
+
if level >= 1:
|
|
228
|
+
_o1(work, labels, protected)
|
|
229
|
+
if level >= 2:
|
|
230
|
+
_o2(work, labels, protected)
|
|
231
|
+
if level >= 3:
|
|
232
|
+
_o3(work, labels, protected)
|
|
233
|
+
# 删除不可达代码后可能暴露新的“跳到下一条”,再跑一次 O1
|
|
234
|
+
_o1(work, labels, protected)
|
|
235
|
+
|
|
236
|
+
return _remap(work, labels, entry_pc)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""v6.2.0 工具链共享基础设施 (mkn / pic / CVM)。
|
|
2
|
+
|
|
3
|
+
本子包刻意不依赖 ``codecin.cin`` / ``codecin.cpu``: 清单解析、包存储、
|
|
4
|
+
Git 与归档都是纯标准库实现, 便于单独测试, 也避免工具启动时加载原生引擎。
|
|
5
|
+
|
|
6
|
+
模块划分:
|
|
7
|
+
|
|
8
|
+
* :mod:`codecin.packaging.toml` —— 最小 TOML 读写 (兼容 Python 3.8, 无第三方依赖);
|
|
9
|
+
* :mod:`codecin.packaging.model` —— ``pic.toml`` / ``mkn.toml`` 清单与语义化版本;
|
|
10
|
+
* :mod:`codecin.packaging.store` —— 包安装存储 (``$PIC_HOME``) 与项目依赖目录;
|
|
11
|
+
* :mod:`codecin.packaging.vcs` —— Git 克隆 / 标签 / 干净工作区检查;
|
|
12
|
+
* :mod:`codecin.packaging.archive` —— 可复现 zip、路径安全解包与校验和。
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from .archive import ( # noqa: F401
|
|
16
|
+
ArchiveError,
|
|
17
|
+
read_checksums,
|
|
18
|
+
read_manifest_member,
|
|
19
|
+
safe_extract,
|
|
20
|
+
sha256_bytes,
|
|
21
|
+
sha256_file,
|
|
22
|
+
write_zip,
|
|
23
|
+
)
|
|
24
|
+
from .model import ( # noqa: F401
|
|
25
|
+
Dependency,
|
|
26
|
+
ManifestError,
|
|
27
|
+
MknManifest,
|
|
28
|
+
PackageMeta,
|
|
29
|
+
find_project_root,
|
|
30
|
+
load_mkn_manifest,
|
|
31
|
+
load_package_manifest,
|
|
32
|
+
satisfies,
|
|
33
|
+
)
|
|
34
|
+
from .store import InstalledPackage, PackageStore, default_store # noqa: F401
|
|
35
|
+
from .toml import TomlError # noqa: F401
|
|
36
|
+
from .toml import dumps as toml_dumps
|
|
37
|
+
from .toml import loads as toml_loads
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
'ArchiveError', 'Dependency', 'InstalledPackage', 'ManifestError',
|
|
41
|
+
'MknManifest', 'PackageMeta', 'PackageStore', 'TomlError',
|
|
42
|
+
'default_store', 'find_project_root', 'load_mkn_manifest',
|
|
43
|
+
'load_package_manifest', 'read_checksums', 'read_manifest_member',
|
|
44
|
+
'safe_extract', 'satisfies', 'sha256_bytes', 'sha256_file', 'toml_dumps',
|
|
45
|
+
'toml_loads', 'write_zip',
|
|
46
|
+
]
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""可复现 zip 归档、路径安全解包与 SHA-256 校验。
|
|
2
|
+
|
|
3
|
+
``.cinpkg`` (pic 包) 与 ``.cvm`` (CVM 模块) 都使用 zip 容器:
|
|
4
|
+
|
|
5
|
+
META-INF/SHA256SUMS # "<sha256> <path>" 逐行
|
|
6
|
+
... # 其余文件
|
|
7
|
+
|
|
8
|
+
写入使用固定时间戳 (1980-01-01), 同样的输入产生逐字节相同的归档;
|
|
9
|
+
解包拒绝绝对路径、盘符、``..`` 与符号链接成员。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import zipfile
|
|
16
|
+
from typing import Dict, Iterable, List, Tuple
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
'ArchiveError', 'is_safe_member', 'read_checksums', 'read_manifest_member',
|
|
20
|
+
'safe_extract', 'sha256_bytes', 'sha256_file', 'write_zip',
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
_FIXED_TIME = (1980, 1, 1, 0, 0, 0)
|
|
24
|
+
_HASH_RE = re.compile(r'^[0-9a-f]{64}$')
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ArchiveError(ValueError):
|
|
28
|
+
"""归档损坏、路径不安全或校验失败。"""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def sha256_bytes(data: bytes) -> str:
|
|
32
|
+
return hashlib.sha256(data).hexdigest()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def sha256_file(path: str) -> str:
|
|
36
|
+
h = hashlib.sha256()
|
|
37
|
+
with open(path, 'rb') as f:
|
|
38
|
+
for chunk in iter(lambda: f.read(1 << 20), b''):
|
|
39
|
+
h.update(chunk)
|
|
40
|
+
return h.hexdigest()
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def is_safe_member(name: str) -> bool:
|
|
44
|
+
"""zip 成员名是否可安全解包。"""
|
|
45
|
+
if not name or '\x00' in name:
|
|
46
|
+
return False
|
|
47
|
+
normalized = name.replace('\\', '/')
|
|
48
|
+
if normalized.startswith('/') or ':' in normalized:
|
|
49
|
+
return False
|
|
50
|
+
if re.match(r'^[A-Za-z]:', normalized):
|
|
51
|
+
return False
|
|
52
|
+
parts = normalized.split('/')
|
|
53
|
+
return all(part not in ('', '.', '..') for part in parts)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _zip_info(name: str, executable: bool = False) -> zipfile.ZipInfo:
|
|
57
|
+
info = zipfile.ZipInfo(name, date_time=_FIXED_TIME)
|
|
58
|
+
info.compress_type = zipfile.ZIP_DEFLATED
|
|
59
|
+
info.create_system = 3 # Unix, 便于跨平台一致
|
|
60
|
+
info.external_attr = (0o755 if executable else 0o644) << 16
|
|
61
|
+
return info
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def write_zip(path: str, entries: Dict[str, bytes]) -> str:
|
|
65
|
+
"""把 ``{成员名: 字节}`` 写为确定性 zip; 返回路径。"""
|
|
66
|
+
path = os.path.abspath(path)
|
|
67
|
+
os.makedirs(os.path.dirname(path) or '.', exist_ok=True)
|
|
68
|
+
for name in entries:
|
|
69
|
+
if not is_safe_member(name):
|
|
70
|
+
raise ArchiveError(f'不安全的归档成员名: {name!r}')
|
|
71
|
+
# 先写临时文件再原子替换, 避免中断留下半个包
|
|
72
|
+
tmp = path + '.tmp'
|
|
73
|
+
with zipfile.ZipFile(tmp, 'w', compression=zipfile.ZIP_DEFLATED) as zf:
|
|
74
|
+
for name in sorted(entries):
|
|
75
|
+
zf.writestr(_zip_info(name), entries[name])
|
|
76
|
+
os.replace(tmp, path)
|
|
77
|
+
return path
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def safe_extract(path: str, dest: str) -> List[str]:
|
|
81
|
+
"""安全解包到 ``dest``; 返回成员名列表。"""
|
|
82
|
+
dest = os.path.abspath(dest)
|
|
83
|
+
os.makedirs(dest, exist_ok=True)
|
|
84
|
+
out: List[str] = []
|
|
85
|
+
try:
|
|
86
|
+
with zipfile.ZipFile(path) as zf:
|
|
87
|
+
for info in zf.infolist():
|
|
88
|
+
name = info.filename
|
|
89
|
+
if name.endswith('/'):
|
|
90
|
+
continue
|
|
91
|
+
if not is_safe_member(name):
|
|
92
|
+
raise ArchiveError(f'归档包含不安全路径: {name!r}')
|
|
93
|
+
mode = (info.external_attr >> 16) & 0o170000
|
|
94
|
+
if mode == 0o120000:
|
|
95
|
+
raise ArchiveError(f'归档包含符号链接, 已拒绝: {name!r}')
|
|
96
|
+
target = os.path.join(dest, *name.split('/'))
|
|
97
|
+
os.makedirs(os.path.dirname(target), exist_ok=True)
|
|
98
|
+
with zf.open(info) as src, open(target, 'wb') as dst:
|
|
99
|
+
for chunk in iter(lambda: src.read(1 << 20), b''):
|
|
100
|
+
dst.write(chunk)
|
|
101
|
+
out.append(name)
|
|
102
|
+
except zipfile.BadZipFile as e:
|
|
103
|
+
raise ArchiveError(f'不是有效的 zip 归档: {path}') from e
|
|
104
|
+
return out
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def read_manifest_member(path: str,
|
|
108
|
+
names: Iterable[str] = ('CVM-INF/MANIFEST.TOML',
|
|
109
|
+
'pic.toml')) -> str:
|
|
110
|
+
"""读取归档中的文本清单 (返回第一个命中的成员)。"""
|
|
111
|
+
try:
|
|
112
|
+
with zipfile.ZipFile(path) as zf:
|
|
113
|
+
existing = set(zf.namelist())
|
|
114
|
+
for name in names:
|
|
115
|
+
if name in existing:
|
|
116
|
+
return zf.read(name).decode('utf-8-sig')
|
|
117
|
+
except zipfile.BadZipFile as e:
|
|
118
|
+
raise ArchiveError(f'不是有效的 zip 归档: {path}') from e
|
|
119
|
+
raise ArchiveError(f'归档中缺少清单文件 ({", ".join(names)}): {path}')
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def read_checksums(path: str,
|
|
123
|
+
member: str = 'META-INF/SHA256SUMS'
|
|
124
|
+
) -> Dict[str, str]:
|
|
125
|
+
"""读取 ``SHA256SUMS`` 成员; 无该成员时返回空 dict。"""
|
|
126
|
+
try:
|
|
127
|
+
with zipfile.ZipFile(path) as zf:
|
|
128
|
+
if member not in zf.namelist():
|
|
129
|
+
return {}
|
|
130
|
+
text = zf.read(member).decode('utf-8')
|
|
131
|
+
except zipfile.BadZipFile as e:
|
|
132
|
+
raise ArchiveError(f'不是有效的 zip 归档: {path}') from e
|
|
133
|
+
out: Dict[str, str] = {}
|
|
134
|
+
for line in text.splitlines():
|
|
135
|
+
line = line.strip()
|
|
136
|
+
if not line:
|
|
137
|
+
continue
|
|
138
|
+
parts = line.split()
|
|
139
|
+
if len(parts) < 2:
|
|
140
|
+
continue
|
|
141
|
+
digest, name = parts[0].lower(), parts[-1].lstrip('*')
|
|
142
|
+
if _HASH_RE.match(digest):
|
|
143
|
+
out[name.replace('\\', '/')] = digest
|
|
144
|
+
return out
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def verify_checksums(path: str,
|
|
148
|
+
member: str = 'META-INF/SHA256SUMS') -> Tuple[int, List[str]]:
|
|
149
|
+
"""校验归档内所有登记文件; 返回 (校验数, 失败列表)。"""
|
|
150
|
+
expected = read_checksums(path, member)
|
|
151
|
+
failures: List[str] = []
|
|
152
|
+
checked = 0
|
|
153
|
+
with zipfile.ZipFile(path) as zf:
|
|
154
|
+
names = set(zf.namelist())
|
|
155
|
+
for name, digest in expected.items():
|
|
156
|
+
if name not in names:
|
|
157
|
+
failures.append(f'{name}: 归档中缺少该文件')
|
|
158
|
+
continue
|
|
159
|
+
actual = sha256_bytes(zf.read(name))
|
|
160
|
+
checked += 1
|
|
161
|
+
if actual != digest:
|
|
162
|
+
failures.append(f'{name}: 校验和不匹配')
|
|
163
|
+
return checked, failures
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def checksums_text(entries: Dict[str, bytes]) -> bytes:
|
|
167
|
+
"""生成 ``SHA256SUMS`` 文本 (按路径排序)。"""
|
|
168
|
+
lines = [f'{sha256_bytes(entries[name])} {name}'
|
|
169
|
+
for name in sorted(entries) if name != 'META-INF/SHA256SUMS']
|
|
170
|
+
return ('\n'.join(lines) + '\n').encode('utf-8')
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def build_archive_entries(files: Dict[str, bytes]) -> Dict[str, bytes]:
|
|
174
|
+
"""在文件映射上追加 ``META-INF/SHA256SUMS``。"""
|
|
175
|
+
entries = dict(files)
|
|
176
|
+
entries['META-INF/SHA256SUMS'] = checksums_text(entries)
|
|
177
|
+
return entries
|