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
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
package mc
|
|
2
|
+
|
|
3
|
+
import (
|
|
4
|
+
"os"
|
|
5
|
+
"os/exec"
|
|
6
|
+
"path/filepath"
|
|
7
|
+
"runtime"
|
|
8
|
+
"testing"
|
|
9
|
+
|
|
10
|
+
"codecin-native/ir"
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
func TestWrapELFHeaders(t *testing.T) {
|
|
14
|
+
code, err := Encode(&ir.Program{Instructions: []ir.Instr{
|
|
15
|
+
{Op: "MOV", Args: []ir.Operand{ir.Reg(0), ir.Imm(7)}},
|
|
16
|
+
{Op: "HALT"},
|
|
17
|
+
}})
|
|
18
|
+
if err != nil {
|
|
19
|
+
t.Fatalf("Encode: %v", err)
|
|
20
|
+
}
|
|
21
|
+
img := WrapELF(&ir.Program{}, code)
|
|
22
|
+
if err := CheckELF(img); err != nil {
|
|
23
|
+
t.Fatalf("CheckELF: %v", err)
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
func TestUnsupportedOpcode(t *testing.T) {
|
|
28
|
+
_, err := Encode(&ir.Program{Instructions: []ir.Instr{{Op: "DIV"}}})
|
|
29
|
+
if err == nil {
|
|
30
|
+
t.Fatal("期望不支持的指令报错")
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// TestRunUnderWSL 真实执行产物: exit(7)。
|
|
35
|
+
func TestRunUnderWSL(t *testing.T) {
|
|
36
|
+
if runtime.GOOS != "windows" {
|
|
37
|
+
t.Skip("仅在 Windows + WSL 下运行")
|
|
38
|
+
}
|
|
39
|
+
if err := exec.Command("wsl", "-e", "echo", "ok").Run(); err != nil {
|
|
40
|
+
t.Skip("WSL 不可用")
|
|
41
|
+
}
|
|
42
|
+
code, err := Encode(&ir.Program{Instructions: []ir.Instr{
|
|
43
|
+
{Op: "MOV", Args: []ir.Operand{ir.Reg(0), ir.Imm(42)}},
|
|
44
|
+
{Op: "HALT"},
|
|
45
|
+
}})
|
|
46
|
+
if err != nil {
|
|
47
|
+
t.Fatalf("Encode: %v", err)
|
|
48
|
+
}
|
|
49
|
+
runELF(t, code, "rc=42")
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// TestLoopUnderWSL 验证 CMP/JNZ/INC 生成的循环: R0 从 0 增到 4 后退出。
|
|
53
|
+
func TestLoopUnderWSL(t *testing.T) {
|
|
54
|
+
if runtime.GOOS != "windows" {
|
|
55
|
+
t.Skip("仅在 Windows + WSL 下运行")
|
|
56
|
+
}
|
|
57
|
+
if err := exec.Command("wsl", "-e", "echo", "ok").Run(); err != nil {
|
|
58
|
+
t.Skip("WSL 不可用")
|
|
59
|
+
}
|
|
60
|
+
prog := &ir.Program{
|
|
61
|
+
Instructions: []ir.Instr{
|
|
62
|
+
{Op: "MOV", Args: []ir.Operand{ir.Reg(0), ir.Imm(0)}},
|
|
63
|
+
{Op: "INC", Args: []ir.Operand{ir.Reg(0)}},
|
|
64
|
+
{Op: "CMP", Args: []ir.Operand{ir.Reg(0), ir.Imm(4)}},
|
|
65
|
+
{Op: "JNZ", Args: []ir.Operand{ir.Label("loop")}},
|
|
66
|
+
{Op: "HALT"},
|
|
67
|
+
},
|
|
68
|
+
Labels: map[string]int{"loop": 1},
|
|
69
|
+
}
|
|
70
|
+
code, err := Encode(prog)
|
|
71
|
+
if err != nil {
|
|
72
|
+
t.Fatalf("Encode: %v", err)
|
|
73
|
+
}
|
|
74
|
+
runELF(t, code, "rc=4")
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
func runELF(t *testing.T, code []byte, want string) {
|
|
78
|
+
t.Helper()
|
|
79
|
+
dir := t.TempDir()
|
|
80
|
+
path := filepath.Join(dir, "prog")
|
|
81
|
+
if err := os.WriteFile(path, WrapELF(&ir.Program{}, code), 0o755); err != nil {
|
|
82
|
+
t.Fatal(err)
|
|
83
|
+
}
|
|
84
|
+
wslPath := "/mnt/" + string(path[0]|0x20) + filepath.ToSlash(path[2:])
|
|
85
|
+
script := `"` + wslPath + `"; echo rc=$?`
|
|
86
|
+
out, err := exec.Command("wsl", "-e", "sh", "-c", script).CombinedOutput()
|
|
87
|
+
if err != nil {
|
|
88
|
+
t.Fatalf("运行失败: %v\n%s", err, out)
|
|
89
|
+
}
|
|
90
|
+
if !contains(string(out), want) {
|
|
91
|
+
t.Fatalf("输出 %q 不含 %q", out, want)
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
func contains(s, sub string) bool {
|
|
96
|
+
for i := 0; i+len(sub) <= len(s); i++ {
|
|
97
|
+
if s[i:i+len(sub)] == sub {
|
|
98
|
+
return true
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return false
|
|
102
|
+
}
|
codecin/native.py
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
"""Go 原生库桥接 (c-shared)。
|
|
2
|
+
|
|
3
|
+
通过 ctypes 加载 Go 编译的共享库 (Windows: codecin_native.dll,
|
|
4
|
+
Linux/Termux: libcodecin_native.so, macOS: libcodecin_native.dylib),
|
|
5
|
+
提供:
|
|
6
|
+
1. 原生字节码 VM (codecin_run_v2) -- 整程序高速执行 (段式内存 ABI)
|
|
7
|
+
2. CROM 压缩/解压 (codecin_crom_pack / codecin_crom_unpack)
|
|
8
|
+
|
|
9
|
+
v2 ABI: 程序内存默认 1 GiB, 不再整块传输 -- 调用方只传初始内存段,
|
|
10
|
+
原生执行后只回传脏段 (64 KiB 页粒度合并)。
|
|
11
|
+
|
|
12
|
+
字节码格式 (UCBC):
|
|
13
|
+
头部: magic[4]='UCBC' version u8 entry u32 instr_count u32
|
|
14
|
+
指令: opcode u8 argc u8
|
|
15
|
+
操作数: kind u8 value i64 extra i64 (小端)
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import ctypes
|
|
19
|
+
import os
|
|
20
|
+
import platform
|
|
21
|
+
import struct
|
|
22
|
+
import sys
|
|
23
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
24
|
+
|
|
25
|
+
from .isa import (
|
|
26
|
+
BC_MAGIC,
|
|
27
|
+
BC_VERSION,
|
|
28
|
+
KIND_COND,
|
|
29
|
+
KIND_FLOAT,
|
|
30
|
+
KIND_IMM,
|
|
31
|
+
KIND_MEM,
|
|
32
|
+
KIND_REG,
|
|
33
|
+
KIND_STR,
|
|
34
|
+
KIND_VEC,
|
|
35
|
+
KIND_VECLANE,
|
|
36
|
+
Cond,
|
|
37
|
+
Constants,
|
|
38
|
+
Opcode,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
Operand = Tuple[Any, ...]
|
|
42
|
+
Instruction = Tuple[str, List[Operand]]
|
|
43
|
+
|
|
44
|
+
# ==================== 字节码编解码 ====================
|
|
45
|
+
|
|
46
|
+
_KIND_MAP = {
|
|
47
|
+
'reg': KIND_REG, 'imm': KIND_IMM, 'vec': KIND_VEC,
|
|
48
|
+
'veclane': KIND_VECLANE, 'mem': KIND_MEM, 'cond': KIND_COND,
|
|
49
|
+
'float': KIND_FLOAT, 'str': KIND_STR,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def encode_operand(op: Operand) -> Tuple[int, int, int]:
|
|
54
|
+
kind = _KIND_MAP.get(op[0])
|
|
55
|
+
if kind is None:
|
|
56
|
+
if op[0] == 'label':
|
|
57
|
+
return KIND_IMM, 0, 0 # 未解析标签 (不应出现)
|
|
58
|
+
raise ValueError(f"Cannot encode operand: {op}")
|
|
59
|
+
if kind == KIND_REG:
|
|
60
|
+
return kind, int(op[1]), 0
|
|
61
|
+
if kind == KIND_IMM:
|
|
62
|
+
return kind, int(op[1]) & 0xFFFFFFFFFFFFFFFF, 0
|
|
63
|
+
if kind == KIND_VEC:
|
|
64
|
+
return kind, int(op[1]), 0
|
|
65
|
+
if kind == KIND_VECLANE:
|
|
66
|
+
return kind, int(op[1]), int(op[2])
|
|
67
|
+
if kind == KIND_MEM:
|
|
68
|
+
base = op[1] if len(op) > 1 else -1
|
|
69
|
+
off = op[2] if len(op) > 2 else 0
|
|
70
|
+
return kind, int(base), int(off) & 0xFFFFFFFFFFFFFFFF
|
|
71
|
+
if kind == KIND_COND:
|
|
72
|
+
return kind, Cond.code(op[1]), 0
|
|
73
|
+
if kind == KIND_FLOAT:
|
|
74
|
+
return kind, struct.unpack('<Q', struct.pack('<d', float(op[1])))[0], 0
|
|
75
|
+
if kind == KIND_STR:
|
|
76
|
+
return kind, int(op[1]), 0
|
|
77
|
+
raise ValueError(f"Cannot encode operand: {op}")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _i64(v: int) -> int:
|
|
81
|
+
v &= 0xFFFFFFFFFFFFFFFF
|
|
82
|
+
return v if v < (1 << 63) else v - (1 << 64)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def decode_operand(kind: int, value: int, extra: int) -> Operand:
|
|
86
|
+
if kind == KIND_REG:
|
|
87
|
+
return ('reg', value)
|
|
88
|
+
if kind == KIND_IMM:
|
|
89
|
+
return ('imm', value)
|
|
90
|
+
if kind == KIND_VEC:
|
|
91
|
+
return ('vec', value)
|
|
92
|
+
if kind == KIND_VECLANE:
|
|
93
|
+
return ('veclane', value, extra)
|
|
94
|
+
if kind == KIND_MEM:
|
|
95
|
+
return ('mem', value, extra)
|
|
96
|
+
if kind == KIND_COND:
|
|
97
|
+
return ('cond', Cond.NAMES[value & 15])
|
|
98
|
+
if kind == KIND_FLOAT:
|
|
99
|
+
return ('float', struct.unpack('<d', struct.pack('<q', _i64(value)))[0])
|
|
100
|
+
if kind == KIND_STR:
|
|
101
|
+
return ('str', value)
|
|
102
|
+
raise ValueError(f"Unknown operand kind: {kind}")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def encode_program(instructions: List[Instruction], entry: int = 0,
|
|
106
|
+
labels: Optional[Dict[str, int]] = None) -> bytes:
|
|
107
|
+
"""编码程序为字节码。labels 用于将 ('label', name) 操作数解析为立即数。"""
|
|
108
|
+
out = bytearray()
|
|
109
|
+
out += BC_MAGIC
|
|
110
|
+
out += struct.pack('<B', BC_VERSION)
|
|
111
|
+
out += struct.pack('<I', entry & 0xFFFFFFFF)
|
|
112
|
+
out += struct.pack('<I', len(instructions) & 0xFFFFFFFF)
|
|
113
|
+
labels = labels or {}
|
|
114
|
+
for opcode, args in instructions:
|
|
115
|
+
op_enum = Constants.OPCODE_NAME_TO_ENUM.get(opcode)
|
|
116
|
+
if op_enum is None:
|
|
117
|
+
raise ValueError(f"Unknown opcode: {opcode}")
|
|
118
|
+
out += struct.pack('<BB', op_enum.value, len(args))
|
|
119
|
+
for arg in args:
|
|
120
|
+
if arg[0] == 'label':
|
|
121
|
+
if arg[1] not in labels:
|
|
122
|
+
raise ValueError(f"Undefined label: {arg[1]}")
|
|
123
|
+
arg = ('imm', labels[arg[1]])
|
|
124
|
+
kind, value, extra = encode_operand(arg)
|
|
125
|
+
out += struct.pack('<Bqq', kind, _i64(value), _i64(extra))
|
|
126
|
+
return bytes(out)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def decode_program(data: bytes) -> Tuple[List[Instruction], int]:
|
|
130
|
+
if data[:4] != BC_MAGIC:
|
|
131
|
+
raise ValueError("Bad bytecode magic")
|
|
132
|
+
version = data[4]
|
|
133
|
+
if version != BC_VERSION:
|
|
134
|
+
raise ValueError(f"Unsupported bytecode version: {version}")
|
|
135
|
+
entry = struct.unpack('<I', data[5:9])[0]
|
|
136
|
+
count = struct.unpack('<I', data[9:13])[0]
|
|
137
|
+
pos = 13
|
|
138
|
+
instructions: List[Instruction] = []
|
|
139
|
+
for _ in range(count):
|
|
140
|
+
op_val, argc = struct.unpack('<BB', data[pos:pos + 2])
|
|
141
|
+
pos += 2
|
|
142
|
+
opcode = Opcode(op_val).name
|
|
143
|
+
args: List[Operand] = []
|
|
144
|
+
for _ in range(argc):
|
|
145
|
+
kind, value, extra = struct.unpack('<Bqq', data[pos:pos + 17])
|
|
146
|
+
pos += 17
|
|
147
|
+
args.append(decode_operand(kind, value, extra))
|
|
148
|
+
instructions.append((opcode, args))
|
|
149
|
+
return instructions, entry
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
# ==================== 原生库加载 ====================
|
|
153
|
+
|
|
154
|
+
_LIB_CACHE: Optional['NativeEngine'] = False # type: ignore
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _os_slug() -> str:
|
|
158
|
+
"""Release 资产命名里的平台段。"""
|
|
159
|
+
system = platform.system()
|
|
160
|
+
if system == 'Windows':
|
|
161
|
+
return 'windows'
|
|
162
|
+
if system == 'Darwin':
|
|
163
|
+
return 'macos'
|
|
164
|
+
return 'linux'
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _arch_slug() -> str:
|
|
168
|
+
"""Release 资产命名里的架构段。"""
|
|
169
|
+
machine = platform.machine().lower()
|
|
170
|
+
if machine in ('x86_64', 'amd64'):
|
|
171
|
+
return 'x64'
|
|
172
|
+
if machine in ('aarch64', 'arm64'):
|
|
173
|
+
return 'arm64'
|
|
174
|
+
if machine in ('i386', 'i686', 'x86'):
|
|
175
|
+
return 'x86'
|
|
176
|
+
return machine
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _lib_candidates() -> List[str]:
|
|
180
|
+
here = os.path.dirname(os.path.abspath(__file__))
|
|
181
|
+
system = platform.system()
|
|
182
|
+
if system == 'Windows':
|
|
183
|
+
prefix, ext = 'codecin_native', 'dll'
|
|
184
|
+
canonical = ['codecin_native.dll']
|
|
185
|
+
elif system == 'Darwin':
|
|
186
|
+
prefix, ext = 'libcodecin_native', 'dylib'
|
|
187
|
+
canonical = ['libcodecin_native.dylib', 'codecin_native.dylib']
|
|
188
|
+
else:
|
|
189
|
+
prefix, ext = 'libcodecin_native', 'so'
|
|
190
|
+
canonical = ['libcodecin_native.so', 'codecin_native.so']
|
|
191
|
+
|
|
192
|
+
# Release 资产带平台/架构后缀 (如 libcodecin_native-linux-arm64.so)。
|
|
193
|
+
# 排在通用名之前: 同一个目录里同时存在两种架构的库时, 必须优先选本机的那个,
|
|
194
|
+
# 否则会拿到"能 dlopen 但跑不了/符号不对"的库。
|
|
195
|
+
specific = [f'{prefix}-{_os_slug()}-{_arch_slug()}.{ext}']
|
|
196
|
+
names = specific + canonical
|
|
197
|
+
|
|
198
|
+
candidates = [os.path.join(here, 'native', n) for n in names]
|
|
199
|
+
candidates += [os.path.join(here, n) for n in names]
|
|
200
|
+
env = os.environ.get('CODECIN_NATIVE_LIB')
|
|
201
|
+
if env:
|
|
202
|
+
candidates.insert(0, env)
|
|
203
|
+
if getattr(sys, 'frozen', False):
|
|
204
|
+
# PyInstaller 打包布局: 二进制位于 exe 目录或 _internal 下
|
|
205
|
+
exe_dir = os.path.dirname(os.path.abspath(sys.executable))
|
|
206
|
+
meipass = getattr(sys, '_MEIPASS', exe_dir)
|
|
207
|
+
candidates += [os.path.join(meipass, n) for n in names]
|
|
208
|
+
candidates += [os.path.join(exe_dir, n) for n in names]
|
|
209
|
+
return candidates
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class NativeEngine:
|
|
213
|
+
def __init__(self, lib: ctypes.CDLL):
|
|
214
|
+
self.lib = lib
|
|
215
|
+
self._configure()
|
|
216
|
+
|
|
217
|
+
def _configure(self) -> None:
|
|
218
|
+
lib = self.lib
|
|
219
|
+
lib.codecin_run_v2.argtypes = [
|
|
220
|
+
ctypes.c_void_p, ctypes.c_int, # 请求缓冲 (bc+段+输入), len
|
|
221
|
+
ctypes.c_longlong, ctypes.c_longlong, # entry, sp
|
|
222
|
+
ctypes.c_longlong, ctypes.c_longlong, # heapBase, memSize
|
|
223
|
+
ctypes.c_longlong, # maxSteps
|
|
224
|
+
ctypes.c_longlong, ctypes.c_longlong, # seed, flags (bit0=sandbox bit1=实时输出)
|
|
225
|
+
]
|
|
226
|
+
lib.codecin_run_v2.restype = ctypes.c_void_p
|
|
227
|
+
lib.codecin_free.argtypes = [ctypes.c_void_p]
|
|
228
|
+
lib.codecin_free.restype = None
|
|
229
|
+
lib.codecin_crom_pack.argtypes = [
|
|
230
|
+
ctypes.c_void_p, ctypes.c_int, ctypes.c_int,
|
|
231
|
+
ctypes.POINTER(ctypes.c_int),
|
|
232
|
+
]
|
|
233
|
+
lib.codecin_crom_pack.restype = ctypes.c_void_p
|
|
234
|
+
lib.codecin_crom_unpack.argtypes = [
|
|
235
|
+
ctypes.c_void_p, ctypes.c_int,
|
|
236
|
+
ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int),
|
|
237
|
+
]
|
|
238
|
+
lib.codecin_crom_unpack.restype = ctypes.c_void_p
|
|
239
|
+
lib.codecin_version.argtypes = []
|
|
240
|
+
lib.codecin_version.restype = ctypes.c_char_p
|
|
241
|
+
|
|
242
|
+
# None (arg_count()/arg(i) 恒为 0/空串), 不影响其余原生能力。
|
|
243
|
+
set_args = getattr(lib, 'codecin_set_args', None)
|
|
244
|
+
if set_args is not None:
|
|
245
|
+
set_args.argtypes = [ctypes.POINTER(ctypes.c_char_p), ctypes.c_int]
|
|
246
|
+
set_args.restype = None
|
|
247
|
+
self._set_args = set_args
|
|
248
|
+
|
|
249
|
+
def version(self) -> str:
|
|
250
|
+
try:
|
|
251
|
+
return self.lib.codecin_version().decode()
|
|
252
|
+
except Exception:
|
|
253
|
+
return "unknown"
|
|
254
|
+
|
|
255
|
+
# ---------------- 原生 VM (v2 段式 ABI) ----------------
|
|
256
|
+
|
|
257
|
+
def _build_request_v2(self, bytecode: bytes, segments, input_data: bytes) -> bytes:
|
|
258
|
+
"""打包 v2 请求缓冲:
|
|
259
|
+
bc_len u32 | bc | seg_count u32 | 每段 (addr u64 + len u32 + data) |
|
|
260
|
+
in_len u32 | input
|
|
261
|
+
(与 native/main.go codecin_run_v2 的解析严格一致)
|
|
262
|
+
"""
|
|
263
|
+
out = bytearray()
|
|
264
|
+
out += struct.pack('<I', len(bytecode))
|
|
265
|
+
out += bytecode
|
|
266
|
+
segs = [(int(a), bytes(d)) for a, d in (segments or []) if d]
|
|
267
|
+
out += struct.pack('<I', len(segs))
|
|
268
|
+
for addr, data in segs:
|
|
269
|
+
out += struct.pack('<QI', addr, len(data))
|
|
270
|
+
out += data
|
|
271
|
+
out += struct.pack('<I', len(input_data))
|
|
272
|
+
out += input_data
|
|
273
|
+
return bytes(out)
|
|
274
|
+
|
|
275
|
+
def run_v2(self, bytecode: bytes, segments, entry: int, sp: int,
|
|
276
|
+
heap_base: int, mem_size: int, input_data: bytes = b'',
|
|
277
|
+
max_steps: int = 0, args: Optional[List[str]] = None,
|
|
278
|
+
seed: Optional[int] = None, sandbox: bool = False,
|
|
279
|
+
stream_output: bool = False
|
|
280
|
+
) -> Optional[Dict[str, Any]]:
|
|
281
|
+
req = self._build_request_v2(bytecode, segments, input_data)
|
|
282
|
+
req_buf = ctypes.create_string_buffer(req, len(req))
|
|
283
|
+
|
|
284
|
+
# 命令行参数注入 (arg_count/arg 的数据源)。每次运行都注入 (空列表
|
|
285
|
+
# 即清空), 避免同一进程内多次运行时上一次的参数残留。
|
|
286
|
+
if self._set_args is not None:
|
|
287
|
+
enc = [a.encode('utf-8') for a in (args or [])]
|
|
288
|
+
arr = (ctypes.c_char_p * len(enc))(*enc)
|
|
289
|
+
self._set_args(arr, len(enc))
|
|
290
|
+
|
|
291
|
+
flags = (1 if sandbox else 0) | (2 if stream_output else 0)
|
|
292
|
+
ptr = self.lib.codecin_run_v2(
|
|
293
|
+
ctypes.cast(req_buf, ctypes.c_void_p), len(req),
|
|
294
|
+
entry, sp, heap_base, mem_size,
|
|
295
|
+
max_steps,
|
|
296
|
+
int(seed) if seed else 0,
|
|
297
|
+
flags,
|
|
298
|
+
)
|
|
299
|
+
if not ptr:
|
|
300
|
+
return None
|
|
301
|
+
try:
|
|
302
|
+
return self._parse_result_v2(ptr)
|
|
303
|
+
finally:
|
|
304
|
+
self.lib.codecin_free(ptr)
|
|
305
|
+
|
|
306
|
+
def _parse_result_v2(self, ptr: int) -> Dict[str, Any]:
|
|
307
|
+
base = ptr
|
|
308
|
+
head = ctypes.string_at(base, 36)
|
|
309
|
+
status = head[0]
|
|
310
|
+
flg = head[1]
|
|
311
|
+
streamed = bool(head[2])
|
|
312
|
+
pc, sp, heap_ptr, steps = struct.unpack_from('<QQQQ', head, 4)
|
|
313
|
+
off = 36
|
|
314
|
+
regs_raw = ctypes.string_at(base + off, 33 * 8)
|
|
315
|
+
off += 33 * 8
|
|
316
|
+
vec_raw = ctypes.string_at(base + off, 32 * 4 * 8)
|
|
317
|
+
off += 32 * 4 * 8
|
|
318
|
+
seg_count = struct.unpack_from(
|
|
319
|
+
'<Q', ctypes.string_at(base + off, 8), 0)[0]
|
|
320
|
+
off += 8
|
|
321
|
+
segments: List[Tuple[int, bytes]] = []
|
|
322
|
+
for _ in range(seg_count):
|
|
323
|
+
hdr = ctypes.string_at(base + off, 16)
|
|
324
|
+
seg_addr, seg_len = struct.unpack('<QQ', hdr)
|
|
325
|
+
off += 16
|
|
326
|
+
data = bytes(ctypes.string_at(base + off, seg_len)) if seg_len else b''
|
|
327
|
+
off += seg_len
|
|
328
|
+
segments.append((seg_addr, data))
|
|
329
|
+
out_len = struct.unpack_from('<Q', ctypes.string_at(base + off, 8), 0)[0]
|
|
330
|
+
off += 8
|
|
331
|
+
out_data = bytes(ctypes.string_at(base + off, out_len)) if out_len else b''
|
|
332
|
+
off += out_len
|
|
333
|
+
err_len = struct.unpack_from('<H', ctypes.string_at(base + off, 2), 0)[0]
|
|
334
|
+
off += 2
|
|
335
|
+
err_msg = ctypes.string_at(base + off, err_len).decode(
|
|
336
|
+
'utf-8', 'replace') if err_len else ''
|
|
337
|
+
|
|
338
|
+
regs = list(struct.unpack('<33Q', regs_raw))
|
|
339
|
+
vec_flat = struct.unpack(f'<{32 * 4}d', vec_raw)
|
|
340
|
+
vec_regs = [list(vec_flat[i * 4:(i + 1) * 4]) for i in range(32)]
|
|
341
|
+
|
|
342
|
+
flags = {'N': bool(flg & 1), 'Z': bool(flg & 2),
|
|
343
|
+
'C': bool(flg & 4), 'V': bool(flg & 8)}
|
|
344
|
+
|
|
345
|
+
error = None
|
|
346
|
+
if status == 2:
|
|
347
|
+
error = err_msg or 'unsupported instruction'
|
|
348
|
+
elif status == 3:
|
|
349
|
+
error = err_msg or 'runtime error'
|
|
350
|
+
|
|
351
|
+
return {
|
|
352
|
+
'status': status,
|
|
353
|
+
'flags': flags,
|
|
354
|
+
'pc': pc,
|
|
355
|
+
'sp': sp,
|
|
356
|
+
'heap_ptr': heap_ptr,
|
|
357
|
+
'steps': steps,
|
|
358
|
+
'regs': regs,
|
|
359
|
+
'vec_regs': vec_regs,
|
|
360
|
+
'segments': segments,
|
|
361
|
+
'output': out_data.decode('utf-8', 'replace'),
|
|
362
|
+
'streamed': streamed,
|
|
363
|
+
'error': error,
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
# ---------------- CROM ----------------
|
|
367
|
+
|
|
368
|
+
def crom_pack(self, mem: bytes, compress: bool) -> Optional[bytes]:
|
|
369
|
+
buf = ctypes.create_string_buffer(bytes(mem), len(mem))
|
|
370
|
+
out_len = ctypes.c_int(0)
|
|
371
|
+
ptr = self.lib.codecin_crom_pack(
|
|
372
|
+
ctypes.cast(buf, ctypes.c_void_p), len(mem),
|
|
373
|
+
1 if compress else 0, ctypes.byref(out_len))
|
|
374
|
+
if not ptr:
|
|
375
|
+
return None
|
|
376
|
+
try:
|
|
377
|
+
return bytes(ctypes.string_at(ptr, out_len.value))
|
|
378
|
+
finally:
|
|
379
|
+
self.lib.codecin_free(ptr)
|
|
380
|
+
|
|
381
|
+
def crom_unpack(self, data: bytes) -> Optional[bytes]:
|
|
382
|
+
buf = ctypes.create_string_buffer(data, len(data))
|
|
383
|
+
mem_len = ctypes.c_int(0)
|
|
384
|
+
flags = ctypes.c_int(0)
|
|
385
|
+
ptr = self.lib.codecin_crom_unpack(
|
|
386
|
+
ctypes.cast(buf, ctypes.c_void_p), len(data),
|
|
387
|
+
ctypes.byref(mem_len), ctypes.byref(flags))
|
|
388
|
+
if not ptr:
|
|
389
|
+
return None
|
|
390
|
+
try:
|
|
391
|
+
return bytes(ctypes.string_at(ptr, mem_len.value))
|
|
392
|
+
finally:
|
|
393
|
+
self.lib.codecin_free(ptr)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def get_engine(logger=None) -> Optional[NativeEngine]:
|
|
397
|
+
"""查找并加载原生库; 加载失败返回 None。
|
|
398
|
+
|
|
399
|
+
v5.9.0 起为 native-only, **没有纯 Python 回退**: 返回 None 表示调用方
|
|
400
|
+
必须按「引擎不可用」处理 (CPU 会抛 CPUSimulatorError), 而不是降级执行。
|
|
401
|
+
"""
|
|
402
|
+
global _LIB_CACHE
|
|
403
|
+
if _LIB_CACHE is not False:
|
|
404
|
+
return _LIB_CACHE
|
|
405
|
+
|
|
406
|
+
engine = None
|
|
407
|
+
failures = []
|
|
408
|
+
for path in _lib_candidates():
|
|
409
|
+
if not os.path.exists(path):
|
|
410
|
+
continue
|
|
411
|
+
try:
|
|
412
|
+
lib = ctypes.CDLL(path)
|
|
413
|
+
engine = NativeEngine(lib)
|
|
414
|
+
if logger:
|
|
415
|
+
logger.debug(f"Loaded native library: {path} ({engine.version()})")
|
|
416
|
+
break
|
|
417
|
+
except (OSError, AttributeError) as e:
|
|
418
|
+
# OSError: 架构不符 / 依赖缺失 / 不是动态库
|
|
419
|
+
# AttributeError: 能加载但缺导出符号或 ABI 版本不符 (例如旁边的旧库)
|
|
420
|
+
# 两种情况都应继续尝试下一个候选, 而不是让整个运行炸掉。
|
|
421
|
+
failures.append((path, e))
|
|
422
|
+
if logger:
|
|
423
|
+
logger.debug(f"Failed to load native library {path}: {e}")
|
|
424
|
+
engine = None
|
|
425
|
+
|
|
426
|
+
if engine is None and failures and logger:
|
|
427
|
+
path, err = failures[-1]
|
|
428
|
+
logger.warning(f"原生库不可用 (v5.9.0 起无解释器回退, 请重建原生库): "
|
|
429
|
+
f"{path} ({err})")
|
|
430
|
+
|
|
431
|
+
_LIB_CACHE = engine
|
|
432
|
+
return engine
|