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.
Files changed (202) hide show
  1. codecin/__init__.py +27 -0
  2. codecin/aot.py +1057 -0
  3. codecin/assembler.py +619 -0
  4. codecin/cbackend.py +3024 -0
  5. codecin/cin.py +4265 -0
  6. codecin/cli.py +670 -0
  7. codecin/codecin_native.dll +0 -0
  8. codecin/config.py +50 -0
  9. codecin/console.py +183 -0
  10. codecin/cpu.py +312 -0
  11. codecin/crom.py +449 -0
  12. codecin/cvm.py +708 -0
  13. codecin/disasm.py +149 -0
  14. codecin/environment.py +176 -0
  15. codecin/errors.py +54 -0
  16. codecin/isa.py +560 -0
  17. codecin/lib/array/pic.toml +10 -0
  18. codecin/lib/array/src/array.cin +103 -0
  19. codecin/lib/bigint/pic.toml +10 -0
  20. codecin/lib/bigint/src/bigint.cin +589 -0
  21. codecin/lib/bits/pic.toml +10 -0
  22. codecin/lib/bits/src/bits.cin +143 -0
  23. codecin/lib/bitset/pic.toml +10 -0
  24. codecin/lib/bitset/src/bitset.cin +374 -0
  25. codecin/lib/codec/pic.toml +10 -0
  26. codecin/lib/codec/src/codec.cin +563 -0
  27. codecin/lib/combin/pic.toml +10 -0
  28. codecin/lib/combin/src/combin.cin +414 -0
  29. codecin/lib/conv/pic.toml +10 -0
  30. codecin/lib/conv/src/conv.cin +151 -0
  31. codecin/lib/cppstd/pic.toml +10 -0
  32. codecin/lib/cppstd/src/cppstd.cin +418 -0
  33. codecin/lib/cstd/pic.toml +10 -0
  34. codecin/lib/cstd/src/cstd.cin +424 -0
  35. codecin/lib/csv/pic.toml +10 -0
  36. codecin/lib/csv/src/csv.cin +405 -0
  37. codecin/lib/dp/pic.toml +10 -0
  38. codecin/lib/dp/src/dp.cin +325 -0
  39. codecin/lib/ffi/pic.toml +10 -0
  40. codecin/lib/ffi/src/ffi.cin +163 -0
  41. codecin/lib/fmt/pic.toml +10 -0
  42. codecin/lib/fmt/src/fmt.cin +325 -0
  43. codecin/lib/frac/pic.toml +10 -0
  44. codecin/lib/frac/src/frac.cin +252 -0
  45. codecin/lib/gostd/pic.toml +10 -0
  46. codecin/lib/gostd/src/gostd.cin +415 -0
  47. codecin/lib/graph/pic.toml +10 -0
  48. codecin/lib/graph/src/graph.cin +367 -0
  49. codecin/lib/gui/pic.toml +10 -0
  50. codecin/lib/gui/src/gui.cin +218 -0
  51. codecin/lib/hash/pic.toml +10 -0
  52. codecin/lib/hash/src/hash.cin +67 -0
  53. codecin/lib/heap/pic.toml +10 -0
  54. codecin/lib/heap/src/heap.cin +199 -0
  55. codecin/lib/io/pic.toml +10 -0
  56. codecin/lib/io/src/io.cin +141 -0
  57. codecin/lib/json/pic.toml +10 -0
  58. codecin/lib/json/src/json.cin +84 -0
  59. codecin/lib/key/pic.toml +10 -0
  60. codecin/lib/key/src/key.cin +78 -0
  61. codecin/lib/math/pic.toml +10 -0
  62. codecin/lib/math/src/math.cin +50 -0
  63. codecin/lib/matrix/pic.toml +10 -0
  64. codecin/lib/matrix/src/matrix.cin +155 -0
  65. codecin/lib/net/pic.toml +10 -0
  66. codecin/lib/net/src/net.cin +171 -0
  67. codecin/lib/path/pic.toml +10 -0
  68. codecin/lib/path/src/path.cin +372 -0
  69. codecin/lib/queue/pic.toml +10 -0
  70. codecin/lib/queue/src/queue.cin +112 -0
  71. codecin/lib/rand/pic.toml +10 -0
  72. codecin/lib/rand/src/rand.cin +46 -0
  73. codecin/lib/set/pic.toml +10 -0
  74. codecin/lib/set/src/set.cin +269 -0
  75. codecin/lib/sort/pic.toml +10 -0
  76. codecin/lib/sort/src/sort.cin +93 -0
  77. codecin/lib/stat/pic.toml +10 -0
  78. codecin/lib/stat/src/stat.cin +138 -0
  79. codecin/lib/str/pic.toml +10 -0
  80. codecin/lib/str/src/str.cin +54 -0
  81. codecin/lib/termux/pic.toml +10 -0
  82. codecin/lib/termux/src/termux.cin +118 -0
  83. codecin/lib/test/pic.toml +10 -0
  84. codecin/lib/test/src/test.cin +74 -0
  85. codecin/lib/text/pic.toml +10 -0
  86. codecin/lib/text/src/text.cin +323 -0
  87. codecin/lib/time/pic.toml +10 -0
  88. codecin/lib/time/src/time.cin +54 -0
  89. codecin/lib/token/pic.toml +10 -0
  90. codecin/lib/token/src/token.cin +183 -0
  91. codecin/lib/tree/pic.toml +10 -0
  92. codecin/lib/tree/src/tree.cin +256 -0
  93. codecin/lib/unionfind/pic.toml +10 -0
  94. codecin/lib/unionfind/src/unionfind.cin +115 -0
  95. codecin/lib/validate/pic.toml +10 -0
  96. codecin/lib/validate/src/validate.cin +148 -0
  97. codecin/lib/vec/pic.toml +10 -0
  98. codecin/lib/vec/src/vec.cin +88 -0
  99. codecin/logger.py +145 -0
  100. codecin/memory.py +306 -0
  101. codecin/mkn.py +916 -0
  102. codecin/native/aot/aot.go +114 -0
  103. codecin/native/aot/stub_main.go.txt +23 -0
  104. codecin/native/build.ps1 +33 -0
  105. codecin/native/build.sh +48 -0
  106. codecin/native/cmd/cincc/main.go +66 -0
  107. codecin/native/compiler/codegen.go +2238 -0
  108. codecin/native/compiler/compile_test.go +1069 -0
  109. codecin/native/compiler/parser.go +1331 -0
  110. codecin/native/compiler/syscalls.go +166 -0
  111. codecin/native/compiler/tokenizer.go +394 -0
  112. codecin/native/compiler/types.go +217 -0
  113. codecin/native/engine/args.go +37 -0
  114. codecin/native/engine/audio.go +402 -0
  115. codecin/native/engine/audio_other.go +105 -0
  116. codecin/native/engine/audio_test.go +279 -0
  117. codecin/native/engine/audio_windows.go +190 -0
  118. codecin/native/engine/canvas.go +271 -0
  119. codecin/native/engine/console_other.go +9 -0
  120. codecin/native/engine/console_windows.go +43 -0
  121. codecin/native/engine/crom.go +86 -0
  122. codecin/native/engine/encode.go +93 -0
  123. codecin/native/engine/engine_test.go +198 -0
  124. codecin/native/engine/ffi_nocgo.go +20 -0
  125. codecin/native/engine/ffi_registry.go +69 -0
  126. codecin/native/engine/ffi_unix.go +109 -0
  127. codecin/native/engine/ffi_windows.go +117 -0
  128. codecin/native/engine/gui.go +209 -0
  129. codecin/native/engine/gui_stub.go +13 -0
  130. codecin/native/engine/gui_test.go +148 -0
  131. codecin/native/engine/gui_windows.go +604 -0
  132. codecin/native/engine/gui_x11.go +723 -0
  133. codecin/native/engine/host_test.go +139 -0
  134. codecin/native/engine/hostcrypto.go +30 -0
  135. codecin/native/engine/hostdesktop.go +173 -0
  136. codecin/native/engine/hostnet.go +127 -0
  137. codecin/native/engine/isa_gen.go +689 -0
  138. codecin/native/engine/keyboard.go +432 -0
  139. codecin/native/engine/keyboard_other.go +94 -0
  140. codecin/native/engine/keyboard_stub.go +17 -0
  141. codecin/native/engine/keyboard_termios_darwin.go +9 -0
  142. codecin/native/engine/keyboard_termios_linux.go +9 -0
  143. codecin/native/engine/keyboard_test.go +246 -0
  144. codecin/native/engine/keyboard_windows.go +208 -0
  145. codecin/native/engine/keyboard_windows_test.go +123 -0
  146. codecin/native/engine/lineedit.go +262 -0
  147. codecin/native/engine/lineedit_test.go +105 -0
  148. codecin/native/engine/lineint_unix.go +17 -0
  149. codecin/native/engine/lineint_windows.go +19 -0
  150. codecin/native/engine/mem_other.go +37 -0
  151. codecin/native/engine/mem_windows.go +33 -0
  152. codecin/native/engine/native.go +640 -0
  153. codecin/native/engine/netsock.go +321 -0
  154. codecin/native/engine/ops_ext.go +515 -0
  155. codecin/native/engine/stdin.go +72 -0
  156. codecin/native/engine/stdin_other.go +9 -0
  157. codecin/native/engine/stdin_windows.go +60 -0
  158. codecin/native/engine/system.go +313 -0
  159. codecin/native/engine/termux.go +180 -0
  160. codecin/native/engine/version_gen.go +7 -0
  161. codecin/native/engine/vkb_darwin.go +62 -0
  162. codecin/native/engine/vkb_linux.go +95 -0
  163. codecin/native/engine/vkb_stub.go +11 -0
  164. codecin/native/engine/vm.go +1677 -0
  165. codecin/native/go.mod +3 -0
  166. codecin/native/ir/ir.go +48 -0
  167. codecin/native/main.go +448 -0
  168. codecin/native/mc/aarch64.go +165 -0
  169. codecin/native/mc/aarch64_test.go +30 -0
  170. codecin/native/mc/elf.go +88 -0
  171. codecin/native/mc/print_test.go +52 -0
  172. codecin/native/mc/x86_64.go +1262 -0
  173. codecin/native/mc/x86_64_test.go +102 -0
  174. codecin/native.py +432 -0
  175. codecin/native_codegen.py +987 -0
  176. codecin/nativegen.py +786 -0
  177. codecin/object.py +539 -0
  178. codecin/optimizer.py +236 -0
  179. codecin/packaging/__init__.py +46 -0
  180. codecin/packaging/archive.py +177 -0
  181. codecin/packaging/model.py +519 -0
  182. codecin/packaging/spec.py +193 -0
  183. codecin/packaging/store.py +372 -0
  184. codecin/packaging/toml.py +541 -0
  185. codecin/packaging/vcs.py +215 -0
  186. codecin/pic.py +1917 -0
  187. codecin/pic_api.py +374 -0
  188. codecin/pic_login.py +519 -0
  189. codecin/pic_registry.py +515 -0
  190. codecin/registers.py +130 -0
  191. codecin/sdgcc.py +493 -0
  192. codecin/stats.py +230 -0
  193. codecin/stdlib.py +138 -0
  194. codecin/toolchain.py +396 -0
  195. codecin/toolkit.py +26 -0
  196. codecin/version.py +260 -0
  197. codecin-7.22.10.dist-info/METADATA +1077 -0
  198. codecin-7.22.10.dist-info/RECORD +202 -0
  199. codecin-7.22.10.dist-info/WHEEL +5 -0
  200. codecin-7.22.10.dist-info/entry_points.txt +5 -0
  201. codecin-7.22.10.dist-info/licenses/LICENSE +7 -0
  202. codecin-7.22.10.dist-info/top_level.txt +1 -0
codecin/cbackend.py ADDED
@@ -0,0 +1,3024 @@
1
+ """AOT 后端: 把 UCBC 指令翻译成 C, 再交给 GCC/Clang 生成机器码。
2
+
3
+ 不再经过 Go: 每条 UCBC 指令展开为一条 C 语句 (寄存器数组 + 显式标志位 +
4
+ 扁平内存), 由 C 编译器做寄存器分配和指令选择。产物是独立可执行文件,
5
+ 可用 :mod:`codecin.toolchain` 交叉编译到
6
+
7
+ * ``x86_64-windows`` (PE)
8
+ * ``x86_64-linux`` (ELF)
9
+ * ``aarch64-linux`` (ELF)
10
+
11
+ 当前实现覆盖整数运算/比较跳转/内存/栈/调用返回/``OUT`` 与少量核心
12
+ syscall; 未实现的指令或 syscall 会在运行期以明确信息退出 (码 70), 不会
13
+ 静默产生错误结果。
14
+ """
15
+
16
+ import os
17
+ import struct
18
+ import subprocess
19
+ import tempfile
20
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
21
+
22
+ from . import toolchain
23
+ from .isa import Constants
24
+
25
+ __all__ = ['CBackendError', 'compile_instructions', 'emit_c', 'supports',
26
+ 'c_target']
27
+
28
+ Instruction = Tuple[str, List[Tuple[Any, ...]]]
29
+ Segments = Sequence[Tuple[int, bytes]]
30
+
31
+ #: 已实现的指令助记符。
32
+ SUPPORTED_OPS = frozenset({
33
+ 'MOV', 'ADD', 'SUB', 'MUL', 'DIV', 'AND', 'OR', 'XOR', 'SHL', 'SHR',
34
+ 'ASR', 'ROR', 'INC', 'DEC', 'MVN', 'CMP',
35
+ 'ADDI', 'LSL', 'LSR', 'XORI', 'ORI', 'ANDI',
36
+ 'PUSH', 'POP', 'CALL', 'BL', 'RET', 'HALT',
37
+ 'LOAD', 'LW', 'LD', 'LB', 'LH', 'LDR',
38
+ 'STORE', 'SW', 'STR', 'SD', 'SB', 'SH',
39
+ 'JMP', 'JZ', 'JE', 'JNZ', 'JL', 'JG',
40
+ 'B', 'CBZ', 'CBNZ', 'OUT', 'SYS',
41
+ })
42
+
43
+ #: 已实现的 SYS 功能号。
44
+ SUPPORTED_SYS = frozenset(set(range(0, 39)) | {43, 44, 45, 46, 47, 48, 49, 50}
45
+ | set(range(51, 61))
46
+ | set(range(61, 68)) | {80, 81, 82, 83, 84, 85, 86,
47
+ 87, 88, 89, 90, 91, 92, 93,
48
+ 94, 95, 96, 97, 98, 99, 100,
49
+ 101, 102, 103, 104, 105, 106,
50
+ 116, 117, 118, 131, 137,
51
+ 145, 146, 147, 148, 149, 150,
52
+ 151, 152, 153, 154, 155, 156,
53
+ 157})
54
+
55
+
56
+ class CBackendError(RuntimeError):
57
+ """C 后端无法生成/编译。"""
58
+
59
+
60
+ #: 运行期未实现时的退出码。
61
+ UNSUPPORTED_EXIT = 70
62
+
63
+ #: ARM64 条件码 -> C 运行时编号 (与 isa.Cond / VM 的 condition() 一致)。
64
+ _COND_CODES = {
65
+ 'EQ': 0, 'NE': 1, 'CS': 2, 'HS': 2, 'CC': 3, 'LO': 3, 'MI': 4, 'PL': 5,
66
+ 'VS': 6, 'VC': 7, 'HI': 8, 'LS': 9, 'GE': 10, 'LT': 11, 'GT': 12,
67
+ 'LE': 13, 'AL': 14, 'NV': 15,
68
+ }
69
+
70
+ _RUNTIME = r'''
71
+ #include <stdint.h>
72
+ #include <stdio.h>
73
+ #include <stdlib.h>
74
+ #include <string.h>
75
+ #include <math.h>
76
+ #include <time.h>
77
+ #include <sys/stat.h>
78
+ #include <dirent.h>
79
+ #ifdef _WIN32
80
+ #include <direct.h>
81
+ #else
82
+ #include <unistd.h>
83
+ #include <fcntl.h>
84
+ #include <termios.h>
85
+ #include <sys/wait.h>
86
+ #endif
87
+
88
+ #define CODECIN_UNSUPPORTED 70
89
+
90
+ static uint64_t R[33]; /* 0..31 通用, 32 = SP */
91
+ static uint8_t *MEM;
92
+ static uint64_t MEMSZ;
93
+ static int ZF, NF, CF, VF;
94
+ static uint64_t HEAPBASE;
95
+ static uint64_t SYSPTR;
96
+ static const char *ERRMSG;
97
+ static FILE *OUTP;
98
+
99
+ static void rt_fail(const char *msg) { if (!ERRMSG) ERRMSG = msg; }
100
+
101
+ static uint64_t rt_reg(int r) { return R[r]; }
102
+ static void rt_set(int r, uint64_t v) { R[r] = v; }
103
+
104
+ static uint64_t rt_add(uint64_t a, uint64_t b) { return a + b; }
105
+ static uint64_t rt_sub(uint64_t a, uint64_t b) { return a - b; }
106
+ static uint64_t rt_mul(uint64_t a, uint64_t b) { return a * b; }
107
+ static uint64_t rt_sdiv(uint64_t a, uint64_t b) {
108
+ if (!b) { rt_fail("Division by zero"); return 0; }
109
+ return (uint64_t)((int64_t)a / (int64_t)b);
110
+ }
111
+ static uint64_t rt_smod(uint64_t a, uint64_t b) {
112
+ if (!b) { rt_fail("Division by zero"); return 0; }
113
+ return (uint64_t)((int64_t)a % (int64_t)b);
114
+ }
115
+ static uint64_t rt_shl(uint64_t a, uint64_t b) { return a << (b & 63); }
116
+ static uint64_t rt_shr(uint64_t a, uint64_t b) { return a >> (b & 63); }
117
+ static uint64_t rt_asr(uint64_t a, uint64_t b) {
118
+ return (uint64_t)((int64_t)a >> (b & 63));
119
+ }
120
+ static uint64_t rt_ror(uint64_t a, uint64_t b) {
121
+ unsigned s = (unsigned)(b & 63);
122
+ return s ? ((a >> s) | (a << (64 - s))) : a;
123
+ }
124
+
125
+ /* NZCV 与 VM 的 setFlagsSub 完全一致 */
126
+ static void rt_cmp(uint64_t a, uint64_t b) {
127
+ uint64_t res = a - b;
128
+ int64_t sa = (int64_t)a, sb = (int64_t)b, sr = sa - sb;
129
+ ZF = (res == 0);
130
+ NF = (res >> 63) != 0;
131
+ CF = (a >= b);
132
+ VF = (sr > INT64_MAX || sr < INT64_MIN);
133
+ }
134
+
135
+ static int rt_bounds(uint64_t addr, uint64_t width) {
136
+ if (addr > MEMSZ || width > MEMSZ - addr) {
137
+ rt_fail("Memory access out of bounds");
138
+ return 0;
139
+ }
140
+ return 1;
141
+ }
142
+
143
+ static int rt_load(int rd, uint64_t addr, int width, int sign) {
144
+ uint64_t v = 0;
145
+ if (!rt_bounds(addr, (uint64_t)width)) return 0;
146
+ memcpy(&v, MEM + addr, (size_t)width);
147
+ if (sign) {
148
+ if (width == 1 && (v & 0x80)) v |= ~(uint64_t)0xFF;
149
+ if (width == 2 && (v & 0x8000)) v |= ~(uint64_t)0xFFFF;
150
+ if (width == 4 && (v & 0x80000000ULL)) v |= ~(uint64_t)0xFFFFFFFFULL;
151
+ }
152
+ R[rd] = v;
153
+ return 1;
154
+ }
155
+
156
+ static int rt_store(uint64_t v, uint64_t addr, int width) {
157
+ if (!rt_bounds(addr, (uint64_t)width)) return 0;
158
+ memcpy(MEM + addr, &v, (size_t)width);
159
+ return 1;
160
+ }
161
+
162
+ static int rt_push(uint64_t v) {
163
+ uint64_t sp = R[32] - 8;
164
+ R[32] = sp;
165
+ if (!rt_bounds(sp, 8)) return 0;
166
+ memcpy(MEM + sp, &v, 8);
167
+ return 1;
168
+ }
169
+
170
+ static int rt_pop(int rd) {
171
+ uint64_t sp = R[32];
172
+ if (sp + 8 > MEMSZ) { rt_fail("Stack underflow"); return 0; }
173
+ memcpy(&R[rd], MEM + sp, 8);
174
+ R[32] = sp + 8;
175
+ return 1;
176
+ }
177
+
178
+ static uint64_t RETADDR;
179
+ static int rt_pop_ret(void) {
180
+ uint64_t sp = R[32];
181
+ if (sp + 8 > MEMSZ) { rt_fail("Stack underflow"); return 0; }
182
+ memcpy(&RETADDR, MEM + sp, 8);
183
+ R[32] = sp + 8;
184
+ return 1;
185
+ }
186
+
187
+ static void rt_out_uint(uint64_t v) {
188
+ if (v == 10) fputc('\n', OUTP);
189
+ else fprintf(OUTP, "%llu", (unsigned long long)v);
190
+ }
191
+
192
+ static void rt_out_str(uint64_t addr) {
193
+ if (addr >= MEMSZ) { rt_fail("String out of bounds"); return; }
194
+ fputs((const char *)(MEM + addr), OUTP);
195
+ }
196
+
197
+ static void rt_out_float(uint64_t bits) {
198
+ double d;
199
+ memcpy(&d, &bits, 8);
200
+ fprintf(OUTP, "%g", d);
201
+ }
202
+
203
+ static void rt_unsupported(const char *what) {
204
+ if (!ERRMSG) ERRMSG = what;
205
+ }
206
+
207
+ static uint64_t HEAPP;
208
+
209
+ static uint64_t rt_strlen(uint64_t addr) {
210
+ if (addr >= MEMSZ) { rt_fail("String out of bounds"); return 0; }
211
+ return (uint64_t)strlen((const char *)(MEM + addr));
212
+ }
213
+
214
+ static void rt_abort(uint64_t addr) {
215
+ if (addr < MEMSZ) rt_fail((const char *)(MEM + addr));
216
+ else rt_fail("abort");
217
+ }
218
+
219
+ static uint64_t rt_rand_state = 1;
220
+ static uint64_t rt_rand(void) {
221
+ rt_rand_state = rt_rand_state * UINT64_C(6364136223846793005) + 1;
222
+ return rt_rand_state >> 1;
223
+ }
224
+
225
+ static int rt_net_init(void); /* 定义在下方网络段 */
226
+
227
+ static int rt_init(uint64_t memsz, uint64_t sp, uint64_t heapbase) {
228
+ MEMSZ = memsz;
229
+ HEAPBASE = heapbase;
230
+ HEAPP = heapbase;
231
+ SYSPTR = heapbase > 8192 ? heapbase - 8192 : 512;
232
+ MEM = (uint8_t *)calloc((size_t)memsz, 1);
233
+ if (!MEM) return 0;
234
+ rt_net_init(); /* 网络不可用不致命: 相关 SYS 会返回 -1 */
235
+ R[32] = sp;
236
+ OUTP = stdout;
237
+ return 1;
238
+ }
239
+
240
+ static int rt_cond(int code) {
241
+ switch (code) {
242
+ case 0: return ZF; /* EQ */
243
+ case 1: return !ZF; /* NE */
244
+ case 2: return CF; /* CS */
245
+ case 3: return !CF; /* CC */
246
+ case 4: return NF; /* MI */
247
+ case 5: return !NF; /* PL */
248
+ case 6: return VF; /* VS */
249
+ case 7: return !VF; /* VC */
250
+ case 8: return CF && !ZF; /* HI */
251
+ case 9: return !CF || ZF; /* LS */
252
+ case 10: return NF == VF; /* GE */
253
+ case 11: return NF != VF; /* LT */
254
+ case 12: return !ZF && NF == VF; /* GT */
255
+ case 13: return ZF || NF != VF; /* LE */
256
+ case 14: return 1; /* AL */
257
+ default: return 0; /* NV */
258
+ }
259
+ }
260
+
261
+ static int rt_allocframe(uint64_t bytes) {
262
+ int64_t guard = (int64_t)(HEAPBASE + 4096);
263
+ int64_t newsp = (int64_t)R[32] - (int64_t)bytes;
264
+ if (newsp < guard) { rt_fail("Stack overflow (frame allocation)"); return 0; }
265
+ R[32] = (uint64_t)newsp;
266
+ R[0] = R[32];
267
+ return 1;
268
+ }
269
+
270
+ /* ---------------- 堆 / 字符串 ---------------- */
271
+
272
+ static uint64_t rt_heap(uint64_t size) {
273
+ uint64_t p = HEAPP;
274
+ size = (size + 15) & ~(uint64_t)15;
275
+ if (p + size > R[32] || p + size < p) {
276
+ rt_fail("Heap exhausted");
277
+ return 0;
278
+ }
279
+ HEAPP = p + size;
280
+ return p;
281
+ }
282
+
283
+ static const char *rt_cstr(uint64_t addr) {
284
+ if (addr >= MEMSZ) { rt_fail("String out of bounds"); return ""; }
285
+ return (const char *)(MEM + addr);
286
+ }
287
+
288
+ static uint64_t rt_sysbuf(void) { return SYSPTR; }
289
+
290
+ static void rt_writesys(const char *s) {
291
+ size_t n = strlen(s);
292
+ if (SYSPTR + n + 1 > MEMSZ) { rt_fail("sysbuf out of bounds"); return; }
293
+ memcpy(MEM + SYSPTR, s, n + 1);
294
+ }
295
+
296
+ static uint64_t rt_dupstr(const char *s) {
297
+ size_t n = strlen(s) + 1;
298
+ uint64_t p = rt_heap((uint64_t)n);
299
+ if (!p) return 0;
300
+ memcpy(MEM + p, s, n);
301
+ return p;
302
+ }
303
+
304
+ static void rt_to_upper(char *s) {
305
+ for (; *s; s++) if (*s >= 'a' && *s <= 'z') *s -= 32;
306
+ }
307
+
308
+ static void rt_to_lower(char *s) {
309
+ for (; *s; s++) if (*s >= 'A' && *s <= 'Z') *s += 32;
310
+ }
311
+
312
+ static int rt_is_space(int c) {
313
+ return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v'
314
+ || c == '\f';
315
+ }
316
+
317
+ static uint64_t rt_trim(uint64_t addr, int left, int right) {
318
+ const char *s = rt_cstr(addr);
319
+ size_t n = strlen(s), b = 0, e = n;
320
+ if (left) while (b < e && rt_is_space((unsigned char)s[b])) b++;
321
+ if (right) while (e > b && rt_is_space((unsigned char)s[e - 1])) e--;
322
+ uint64_t p = rt_heap((uint64_t)(e - b) + 1);
323
+ if (!p) return 0;
324
+ memcpy(MEM + p, s + b, e - b);
325
+ MEM[p + (e - b)] = 0;
326
+ return p;
327
+ }
328
+
329
+ static uint64_t rt_substr(uint64_t src, uint64_t start, uint64_t length) {
330
+ const char *s = rt_cstr(src);
331
+ int64_t n = (int64_t)strlen(s);
332
+ int64_t st = (int64_t)start > n ? n : ((int64_t)start > 0 ? (int64_t)start : 0);
333
+ int64_t len = (int64_t)length > 0 ? (int64_t)length : 0;
334
+ int64_t end = st + len;
335
+ if (end > n) end = n;
336
+ uint64_t p = rt_heap((uint64_t)(end - st) + 1);
337
+ if (!p) return 0;
338
+ memcpy(MEM + p, s + st, (size_t)(end - st));
339
+ MEM[p + (uint64_t)(end - st)] = 0;
340
+ return p;
341
+ }
342
+
343
+ static uint64_t rt_itoa(int64_t v) {
344
+ char buf[32];
345
+ snprintf(buf, sizeof(buf), "%lld", (long long)v);
346
+ rt_writesys(buf);
347
+ return SYSPTR;
348
+ }
349
+
350
+ static uint64_t rt_ftoa(uint64_t bits) {
351
+ double d;
352
+ char buf[64];
353
+ memcpy(&d, &bits, 8);
354
+ snprintf(buf, sizeof(buf), "%g", d);
355
+ rt_writesys(buf);
356
+ return SYSPTR;
357
+ }
358
+
359
+ static uint64_t rt_boolstr(uint64_t v) {
360
+ rt_writesys(v ? "true" : "false");
361
+ return SYSPTR;
362
+ }
363
+
364
+ static uint64_t rt_strconcat(uint64_t a, uint64_t b) {
365
+ const char *sa = rt_cstr(a);
366
+ const char *sb = rt_cstr(b);
367
+ size_t na = strlen(sa), nb = strlen(sb);
368
+ uint64_t p = rt_heap((uint64_t)(na + nb + 1));
369
+ if (!p) return 0;
370
+ memcpy(MEM + p, sa, na);
371
+ memcpy(MEM + p + na, sb, nb + 1);
372
+ return p;
373
+ }
374
+
375
+ static uint64_t rt_strcpy(uint64_t dst, uint64_t src, int append) {
376
+ const char *s = rt_cstr(src);
377
+ size_t n = strlen(s);
378
+ uint64_t at = dst;
379
+ if (append) {
380
+ if (at >= MEMSZ) { rt_fail("String out of bounds"); return dst; }
381
+ at += strlen((const char *)(MEM + at));
382
+ }
383
+ if (at + n + 1 > MEMSZ) { rt_fail("String out of bounds"); return dst; }
384
+ memcpy(MEM + at, s, n + 1);
385
+ return dst;
386
+ }
387
+
388
+ static uint64_t rt_strcmp(uint64_t a, uint64_t b) {
389
+ const char *sa = rt_cstr(a);
390
+ const char *sb = rt_cstr(b);
391
+ while (*sa && *sa == *sb) { sa++; sb++; }
392
+ return (uint64_t)(int64_t)((unsigned char)*sa - (unsigned char)*sb);
393
+ }
394
+
395
+ static uint64_t rt_indexof(uint64_t hay, uint64_t needle) {
396
+ const char *found = strstr(rt_cstr(hay), rt_cstr(needle));
397
+ return found ? (uint64_t)(found - (const char *)MEM) : (uint64_t)-1;
398
+ }
399
+
400
+ /* ---------------- 文件系统 ---------------- */
401
+
402
+ static uint64_t rt_empty(void) {
403
+ uint64_t p = rt_heap(1);
404
+ if (p) MEM[p] = 0;
405
+ return p;
406
+ }
407
+
408
+ static uint64_t rt_readfile(const char *path) {
409
+ FILE *f = fopen(path, "rb");
410
+ long n;
411
+ uint64_t p;
412
+ size_t got;
413
+ if (!f) return rt_empty();
414
+ if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return rt_empty(); }
415
+ n = ftell(f);
416
+ if (n < 0) { fclose(f); return rt_empty(); }
417
+ rewind(f);
418
+ p = rt_heap((uint64_t)n + 1);
419
+ if (!p) { fclose(f); return rt_empty(); }
420
+ got = fread(MEM + p, 1, (size_t)n, f);
421
+ MEM[p + got] = 0;
422
+ fclose(f);
423
+ return p;
424
+ }
425
+
426
+ static int rt_writefile(const char *path, const char *data, int append) {
427
+ FILE *f = fopen(path, append ? "ab" : "wb");
428
+ size_t n;
429
+ int ok;
430
+ if (!f) return -1;
431
+ n = strlen(data);
432
+ ok = (fwrite(data, 1, n, f) == n);
433
+ if (fclose(f) != 0) ok = 0;
434
+ return ok ? 0 : -1;
435
+ }
436
+
437
+ static uint64_t rt_fileexists(const char *path) {
438
+ FILE *f = fopen(path, "rb");
439
+ if (!f) return 0;
440
+ fclose(f);
441
+ return 1;
442
+ }
443
+
444
+ static uint64_t rt_filedelete(const char *path) {
445
+ return remove(path) == 0 ? 0 : (uint64_t)-1;
446
+ }
447
+
448
+ static uint64_t rt_filesize(const char *path) {
449
+ FILE *f = fopen(path, "rb");
450
+ long n;
451
+ if (!f) return (uint64_t)-1;
452
+ if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return (uint64_t)-1; }
453
+ n = ftell(f);
454
+ fclose(f);
455
+ return n < 0 ? (uint64_t)-1 : (uint64_t)n;
456
+ }
457
+
458
+ static int rt_mkdir_one(const char *path) {
459
+ #ifdef _WIN32
460
+ return _mkdir(path);
461
+ #else
462
+ return mkdir(path, 0755);
463
+ #endif
464
+ }
465
+
466
+ static uint64_t rt_mkdirs(const char *path) {
467
+ char buf[1024];
468
+ size_t n = strlen(path);
469
+ char *p;
470
+ if (n == 0 || n >= sizeof(buf)) return (uint64_t)-1;
471
+ memcpy(buf, path, n + 1);
472
+ for (p = buf + 1; *p; p++) {
473
+ if (*p == '/' || *p == '\\') {
474
+ char save = *p;
475
+ *p = 0;
476
+ rt_mkdir_one(buf);
477
+ *p = save;
478
+ }
479
+ }
480
+ return rt_mkdir_one(buf) == 0 ? 0 : (uint64_t)-1;
481
+ }
482
+
483
+ /* ---------------- 目录 / 环境 ---------------- */
484
+
485
+ static int rt_cmp_name(const void *a, const void *b) {
486
+ return strcmp(*(char *const *)a, *(char *const *)b);
487
+ }
488
+
489
+ static uint64_t rt_dirlist(const char *path) {
490
+ DIR *d = opendir(path);
491
+ char **names = NULL;
492
+ size_t count = 0, cap = 0, total = 0, i, at;
493
+ struct dirent *ent;
494
+ uint64_t out;
495
+ if (!d) return rt_empty();
496
+ while ((ent = readdir(d)) != NULL) {
497
+ char full[2048];
498
+ struct stat st;
499
+ size_t n;
500
+ int is_dir = 0;
501
+ if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) continue;
502
+ snprintf(full, sizeof(full), "%s/%s", path, ent->d_name);
503
+ if (stat(full, &st) == 0 && S_ISDIR(st.st_mode)) is_dir = 1;
504
+ n = strlen(ent->d_name) + (is_dir ? 2 : 1);
505
+ if (count == cap) {
506
+ cap = cap ? cap * 2 : 16;
507
+ names = (char **)realloc(names, cap * sizeof(char *));
508
+ if (!names) { closedir(d); return rt_empty(); }
509
+ }
510
+ names[count] = (char *)malloc(n);
511
+ if (!names[count]) { closedir(d); return rt_empty(); }
512
+ snprintf(names[count], n, "%s%s", ent->d_name, is_dir ? "/" : "");
513
+ count++;
514
+ }
515
+ closedir(d);
516
+ qsort(names, count, sizeof(char *), rt_cmp_name);
517
+ for (i = 0; i < count; i++) total += strlen(names[i]) + 1;
518
+ out = rt_heap((uint64_t)total + 1);
519
+ if (!out) { for (i = 0; i < count; i++) free(names[i]); free(names); return 0; }
520
+ at = 0;
521
+ for (i = 0; i < count; i++) {
522
+ size_t n = strlen(names[i]);
523
+ if (i) MEM[out + at++] = '\n';
524
+ memcpy(MEM + out + at, names[i], n);
525
+ at += n;
526
+ free(names[i]);
527
+ }
528
+ MEM[out + at] = 0;
529
+ free(names);
530
+ return out;
531
+ }
532
+
533
+ static uint64_t rt_getenv(const char *name) {
534
+ const char *v = getenv(name);
535
+ return rt_dupstr(v ? v : "");
536
+ }
537
+
538
+ static uint64_t rt_setenv(const char *name, const char *value) {
539
+ #ifdef _WIN32
540
+ return _putenv_s(name, value) == 0 ? 0 : (uint64_t)-1;
541
+ #else
542
+ return setenv(name, value, 1) == 0 ? 0 : (uint64_t)-1;
543
+ #endif
544
+ }
545
+
546
+ static uint64_t rt_osname(void) {
547
+ #if defined(_WIN32)
548
+ return rt_dupstr("windows");
549
+ #elif defined(__APPLE__)
550
+ return rt_dupstr("darwin");
551
+ #else
552
+ return rt_dupstr("linux");
553
+ #endif
554
+ }
555
+
556
+ static uint64_t rt_hostname(void) {
557
+ #if defined(_WIN32)
558
+ const char *name = getenv("COMPUTERNAME");
559
+ return rt_dupstr(name ? name : "");
560
+ #else
561
+ char buf[256];
562
+ if (gethostname(buf, sizeof(buf)) != 0) return rt_empty();
563
+ buf[sizeof(buf) - 1] = 0;
564
+ return rt_dupstr(buf);
565
+ #endif
566
+ }
567
+
568
+ static uint64_t rt_username(void) {
569
+ #if defined(_WIN32)
570
+ /* 与 Go 的 user.Current() 对齐: Windows 返回 DOMAIN\user */
571
+ const char *user = getenv("USERNAME");
572
+ const char *domain = getenv("USERDOMAIN");
573
+ char buf[512];
574
+ if (user && *user) {
575
+ if (domain && *domain) {
576
+ snprintf(buf, sizeof(buf), "%s\\%s", domain, user);
577
+ return rt_dupstr(buf);
578
+ }
579
+ return rt_dupstr(user);
580
+ }
581
+ return rt_empty();
582
+ #else
583
+ static const char *keys[] = {"USER", "USERNAME", "LOGNAME"};
584
+ size_t i;
585
+ for (i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
586
+ const char *v = getenv(keys[i]);
587
+ if (v && *v) return rt_dupstr(v);
588
+ }
589
+ return rt_empty();
590
+ #endif
591
+ }
592
+
593
+ static uint64_t rt_cwd(void) {
594
+ char buf[4096];
595
+ return getcwd(buf, sizeof(buf)) ? rt_dupstr(buf) : rt_empty();
596
+ }
597
+
598
+ static uint64_t rt_homedir(void) {
599
+ const char *home = getenv("HOME");
600
+ if (!home || !*home) home = getenv("USERPROFILE");
601
+ return rt_dupstr(home ? home : "");
602
+ }
603
+
604
+ /* ---------------- 网络 (TCP / DNS) ---------------- */
605
+
606
+ #ifdef _WIN32
607
+ #include <winsock2.h>
608
+ #include <ws2tcpip.h>
609
+ #include <windows.h>
610
+ typedef SOCKET rt_sock_t;
611
+ #define RT_BAD_SOCK INVALID_SOCKET
612
+ #else
613
+ #include <sys/socket.h>
614
+ #include <netinet/in.h>
615
+ #include <arpa/inet.h>
616
+ #include <netdb.h>
617
+ typedef int rt_sock_t;
618
+ #define RT_BAD_SOCK (-1)
619
+ #endif
620
+
621
+ #define RT_MAX_SOCKS 64
622
+ static rt_sock_t rt_socks[RT_MAX_SOCKS];
623
+ static int rt_sock_open[RT_MAX_SOCKS];
624
+
625
+ static int rt_net_init(void) {
626
+ #ifdef _WIN32
627
+ WSADATA w;
628
+ return WSAStartup(MAKEWORD(2, 2), &w) == 0;
629
+ #else
630
+ return 1;
631
+ #endif
632
+ }
633
+
634
+ static int rt_sock_register(rt_sock_t s) {
635
+ int i;
636
+ for (i = 1; i < RT_MAX_SOCKS; i++) {
637
+ if (!rt_sock_open[i]) {
638
+ rt_socks[i] = s;
639
+ rt_sock_open[i] = 1;
640
+ return i;
641
+ }
642
+ }
643
+ return -1;
644
+ }
645
+
646
+ static rt_sock_t rt_sock_get(uint64_t fd) {
647
+ if (fd == 0 || fd >= RT_MAX_SOCKS || !rt_sock_open[fd]) return RT_BAD_SOCK;
648
+ return rt_socks[fd];
649
+ }
650
+
651
+ static void rt_sock_release(uint64_t fd) {
652
+ if (fd > 0 && fd < RT_MAX_SOCKS && rt_sock_open[fd]) {
653
+ #ifdef _WIN32
654
+ closesocket(rt_socks[fd]);
655
+ #else
656
+ close(rt_socks[fd]);
657
+ #endif
658
+ rt_sock_open[fd] = 0;
659
+ }
660
+ }
661
+
662
+ static uint64_t rt_dns_lookup(const char *host) {
663
+ struct addrinfo hints, *res = NULL, *it;
664
+ char text[64];
665
+ memset(&hints, 0, sizeof(hints));
666
+ hints.ai_family = AF_INET; /* 与 VM 一致: 优先 IPv4 */
667
+ hints.ai_socktype = SOCK_STREAM;
668
+ if (getaddrinfo(host, NULL, &hints, &res) != 0 || !res) {
669
+ hints.ai_family = AF_UNSPEC;
670
+ if (getaddrinfo(host, NULL, &hints, &res) != 0 || !res) {
671
+ return rt_empty();
672
+ }
673
+ }
674
+ for (it = res; it; it = it->ai_next) {
675
+ if (it->ai_family == AF_INET) {
676
+ struct sockaddr_in *sa = (struct sockaddr_in *)it->ai_addr;
677
+ if (inet_ntop(AF_INET, &sa->sin_addr, text, sizeof(text))) {
678
+ freeaddrinfo(res);
679
+ return rt_dupstr(text);
680
+ }
681
+ }
682
+ }
683
+ for (it = res; it; it = it->ai_next) {
684
+ if (it->ai_family == AF_INET6) {
685
+ struct sockaddr_in6 *sa = (struct sockaddr_in6 *)it->ai_addr;
686
+ if (inet_ntop(AF_INET6, &sa->sin6_addr, text, sizeof(text))) {
687
+ freeaddrinfo(res);
688
+ return rt_dupstr(text);
689
+ }
690
+ }
691
+ }
692
+ freeaddrinfo(res);
693
+ return rt_empty();
694
+ }
695
+
696
+ static uint64_t rt_tcp_dial(const char *host, uint64_t port) {
697
+ struct addrinfo hints, *res = NULL, *it;
698
+ char service[16];
699
+ rt_sock_t s = RT_BAD_SOCK;
700
+ int id;
701
+ if (!host || !*host || port == 0 || port > 65535) return (uint64_t)-1;
702
+ snprintf(service, sizeof(service), "%u", (unsigned)port);
703
+ memset(&hints, 0, sizeof(hints));
704
+ hints.ai_family = AF_UNSPEC;
705
+ hints.ai_socktype = SOCK_STREAM;
706
+ if (getaddrinfo(host, service, &hints, &res) != 0 || !res)
707
+ return (uint64_t)-1;
708
+ for (it = res; it; it = it->ai_next) {
709
+ s = socket(it->ai_family, it->ai_socktype, it->ai_protocol);
710
+ if (s == RT_BAD_SOCK) continue;
711
+ if (connect(s, it->ai_addr, (int)it->ai_addrlen) == 0) break;
712
+ #ifdef _WIN32
713
+ closesocket(s);
714
+ #else
715
+ close(s);
716
+ #endif
717
+ s = RT_BAD_SOCK;
718
+ }
719
+ freeaddrinfo(res);
720
+ if (s == RT_BAD_SOCK) return (uint64_t)-1;
721
+ id = rt_sock_register(s);
722
+ if (id < 0) {
723
+ #ifdef _WIN32
724
+ closesocket(s);
725
+ #else
726
+ close(s);
727
+ #endif
728
+ return (uint64_t)-1;
729
+ }
730
+ return (uint64_t)id;
731
+ }
732
+
733
+ static uint64_t rt_tcp_send(uint64_t fd, uint64_t buf, uint64_t n) {
734
+ rt_sock_t s = rt_sock_get(fd);
735
+ size_t sent = 0;
736
+ if (s == RT_BAD_SOCK || n > (16u << 20)) return (uint64_t)-1;
737
+ if (n == 0) return 0;
738
+ if (buf >= MEMSZ || n > MEMSZ - buf) return (uint64_t)-1;
739
+ while (sent < (size_t)n) {
740
+ int k = send(s, (const char *)(MEM + buf) + sent,
741
+ (int)((size_t)n - sent), 0);
742
+ if (k <= 0) return sent ? (uint64_t)sent : (uint64_t)-1;
743
+ sent += (size_t)k;
744
+ }
745
+ return (uint64_t)sent;
746
+ }
747
+
748
+ static uint64_t rt_tcp_recv(uint64_t fd, uint64_t buf, uint64_t max) {
749
+ rt_sock_t s = rt_sock_get(fd);
750
+ int k;
751
+ if (s == RT_BAD_SOCK || max > (8u << 20)) return (uint64_t)-1;
752
+ if (max == 0) return 0;
753
+ if (buf >= MEMSZ || max > MEMSZ - buf) return 0;
754
+ k = recv(s, (char *)(MEM + buf), (int)max, 0);
755
+ if (k < 0) return (uint64_t)-1;
756
+ return (uint64_t)k;
757
+ }
758
+
759
+ static uint64_t rt_tcp_close(uint64_t fd) {
760
+ if (rt_sock_get(fd) == RT_BAD_SOCK) return (uint64_t)-1;
761
+ rt_sock_release(fd);
762
+ return 0;
763
+ }
764
+
765
+ /* ---------------- HTTP 客户端 (SYS 145/146) ---------------- */
766
+
767
+ static int64_t LASTHTTPST = -1;
768
+
769
+ static rt_sock_t rt_connect_host(const char *host, const char *port) {
770
+ struct addrinfo hints, *res = NULL, *it;
771
+ rt_sock_t s = RT_BAD_SOCK;
772
+ memset(&hints, 0, sizeof(hints));
773
+ hints.ai_family = AF_UNSPEC;
774
+ hints.ai_socktype = SOCK_STREAM;
775
+ if (getaddrinfo(host, port, &hints, &res) != 0 || !res) return RT_BAD_SOCK;
776
+ for (it = res; it; it = it->ai_next) {
777
+ s = socket(it->ai_family, it->ai_socktype, it->ai_protocol);
778
+ if (s == RT_BAD_SOCK) continue;
779
+ if (connect(s, it->ai_addr, (int)it->ai_addrlen) == 0) break;
780
+ #ifdef _WIN32
781
+ closesocket(s);
782
+ #else
783
+ close(s);
784
+ #endif
785
+ s = RT_BAD_SOCK;
786
+ }
787
+ freeaddrinfo(res);
788
+ return s;
789
+ }
790
+
791
+ static int rt_url_parse(const char *url, char *host, size_t hn,
792
+ char *port, size_t pn, char *path, size_t pathn) {
793
+ const char *p = url;
794
+ const char *slash;
795
+ size_t n;
796
+ if (strncmp(p, "http://", 7) == 0) p += 7;
797
+ else if (strncmp(p, "https://", 8) == 0) return 0; /* 无 TLS 实现 */
798
+ slash = strchr(p, '/');
799
+ n = slash ? (size_t)(slash - p) : strlen(p);
800
+ if (n == 0 || n >= hn) return 0;
801
+ memcpy(host, p, n);
802
+ host[n] = 0;
803
+ {
804
+ char *colon = strrchr(host, ':');
805
+ if (colon) {
806
+ *colon = 0;
807
+ snprintf(port, pn, "%s", colon + 1);
808
+ } else {
809
+ snprintf(port, pn, "80");
810
+ }
811
+ }
812
+ snprintf(path, pathn, "%s", slash ? slash : "/");
813
+ return 1;
814
+ }
815
+
816
+ static uint64_t rt_http(const char *method, const char *url,
817
+ const char *headers, const char *body) {
818
+ char host[256], port[8], path[1024];
819
+ char head[8192];
820
+ char extra[4096];
821
+ char *resp = NULL;
822
+ size_t cap = 0, len = 0;
823
+ rt_sock_t s;
824
+ int n;
825
+ const char *body_start;
826
+ uint64_t out;
827
+ LASTHTTPST = -1;
828
+ if (!rt_url_parse(url, host, sizeof(host), port, sizeof(port),
829
+ path, sizeof(path)))
830
+ return rt_empty();
831
+ s = rt_connect_host(host, port);
832
+ if (s == RT_BAD_SOCK) return rt_empty();
833
+
834
+ extra[0] = 0;
835
+ if (headers && *headers) {
836
+ size_t hn = strlen(headers);
837
+ snprintf(extra, sizeof(extra), "%s%s", headers,
838
+ headers[hn - 1] == '\n' ? "" : "\r\n");
839
+ }
840
+ n = snprintf(head, sizeof(head),
841
+ "%s %s HTTP/1.0\r\nHost: %s\r\nConnection: close\r\n%s"
842
+ "Content-Length: %lu\r\n\r\n",
843
+ method, path, host, extra,
844
+ (unsigned long)(body ? strlen(body) : 0));
845
+ if (send(s, head, n, 0) != n) {
846
+ #ifdef _WIN32
847
+ closesocket(s);
848
+ #else
849
+ close(s);
850
+ #endif
851
+ return rt_empty();
852
+ }
853
+ if (body && *body) {
854
+ size_t bn = strlen(body);
855
+ send(s, body, (int)bn, 0);
856
+ }
857
+ for (;;) {
858
+ char chunk[4096];
859
+ int k;
860
+ if (len > (8u << 20)) break; /* 8 MiB 上限 */
861
+ k = recv(s, chunk, (int)sizeof(chunk), 0);
862
+ if (k <= 0) break;
863
+ if (len + (size_t)k + 1 > cap) {
864
+ size_t ncap = cap ? cap * 2 : 8192;
865
+ char *grown;
866
+ while (ncap < len + (size_t)k + 1) ncap *= 2;
867
+ grown = (char *)realloc(resp, ncap);
868
+ if (!grown) { free(resp); resp = NULL; break; }
869
+ resp = grown;
870
+ cap = ncap;
871
+ }
872
+ memcpy(resp + len, chunk, (size_t)k);
873
+ len += (size_t)k;
874
+ }
875
+ #ifdef _WIN32
876
+ closesocket(s);
877
+ #else
878
+ close(s);
879
+ #endif
880
+ if (!resp) return rt_empty();
881
+ resp[len] = 0;
882
+ if (strncmp(resp, "HTTP/", 5) == 0) {
883
+ const char *sp = strchr(resp, ' ');
884
+ LASTHTTPST = sp ? strtoll(sp + 1, NULL, 10) : -1;
885
+ }
886
+ body_start = strstr(resp, "\r\n\r\n");
887
+ out = rt_dupstr(body_start ? body_start + 4 : resp);
888
+ free(resp);
889
+ return out;
890
+ }
891
+
892
+ static uint64_t rt_tcp_listen(uint64_t port) {
893
+ struct sockaddr_in addr;
894
+ rt_sock_t s;
895
+ int id;
896
+ if (port == 0 || port > 65535) return (uint64_t)-1;
897
+ s = socket(AF_INET, SOCK_STREAM, 0);
898
+ if (s == RT_BAD_SOCK) return (uint64_t)-1;
899
+ memset(&addr, 0, sizeof(addr));
900
+ addr.sin_family = AF_INET;
901
+ addr.sin_addr.s_addr = htonl(INADDR_ANY);
902
+ addr.sin_port = htons((unsigned short)port);
903
+ #ifdef _WIN32
904
+ {
905
+ BOOL reuse = TRUE;
906
+ setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&reuse,
907
+ sizeof(reuse));
908
+ }
909
+ #else
910
+ {
911
+ int reuse = 1;
912
+ setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
913
+ }
914
+ #endif
915
+ if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) != 0 ||
916
+ listen(s, 16) != 0) {
917
+ #ifdef _WIN32
918
+ closesocket(s);
919
+ #else
920
+ close(s);
921
+ #endif
922
+ return (uint64_t)-1;
923
+ }
924
+ id = rt_sock_register(s);
925
+ if (id < 0) {
926
+ #ifdef _WIN32
927
+ closesocket(s);
928
+ #else
929
+ close(s);
930
+ #endif
931
+ return (uint64_t)-1;
932
+ }
933
+ return (uint64_t)id;
934
+ }
935
+
936
+ static uint64_t rt_tcp_accept(uint64_t lfd) {
937
+ rt_sock_t l = rt_sock_get(lfd);
938
+ rt_sock_t c;
939
+ int id;
940
+ if (l == RT_BAD_SOCK) return (uint64_t)-1;
941
+ c = accept(l, NULL, NULL);
942
+ if (c == RT_BAD_SOCK) return (uint64_t)-1;
943
+ id = rt_sock_register(c);
944
+ if (id < 0) {
945
+ #ifdef _WIN32
946
+ closesocket(c);
947
+ #else
948
+ close(c);
949
+ #endif
950
+ return (uint64_t)-1;
951
+ }
952
+ return (uint64_t)id;
953
+ }
954
+
955
+ static uint64_t rt_udp_open(uint64_t port) {
956
+ struct sockaddr_in addr;
957
+ rt_sock_t s = socket(AF_INET, SOCK_DGRAM, 0);
958
+ int id;
959
+ if (s == RT_BAD_SOCK) return (uint64_t)-1;
960
+ memset(&addr, 0, sizeof(addr));
961
+ addr.sin_family = AF_INET;
962
+ addr.sin_addr.s_addr = htonl(INADDR_ANY);
963
+ addr.sin_port = htons((unsigned short)port);
964
+ if (port > 0 && bind(s, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
965
+ #ifdef _WIN32
966
+ closesocket(s);
967
+ #else
968
+ close(s);
969
+ #endif
970
+ return (uint64_t)-1;
971
+ }
972
+ id = rt_sock_register(s);
973
+ if (id < 0) {
974
+ #ifdef _WIN32
975
+ closesocket(s);
976
+ #else
977
+ close(s);
978
+ #endif
979
+ return (uint64_t)-1;
980
+ }
981
+ return (uint64_t)id;
982
+ }
983
+
984
+ static uint64_t rt_udp_sendto(uint64_t fd, const char *host, uint64_t port,
985
+ uint64_t buf, uint64_t n) {
986
+ rt_sock_t s = rt_sock_get(fd);
987
+ struct sockaddr_in addr;
988
+ struct addrinfo hints, *res = NULL;
989
+ struct sockaddr_in *sa;
990
+ int k;
991
+ if (s == RT_BAD_SOCK || port == 0 || port > 65535) return (uint64_t)-1;
992
+ if (buf >= MEMSZ || n > MEMSZ - buf || n > (16u << 20)) return (uint64_t)-1;
993
+ memset(&hints, 0, sizeof(hints));
994
+ hints.ai_family = AF_INET;
995
+ hints.ai_socktype = SOCK_DGRAM;
996
+ if (getaddrinfo(host, NULL, &hints, &res) != 0 || !res) return (uint64_t)-1;
997
+ sa = (struct sockaddr_in *)res->ai_addr;
998
+ memset(&addr, 0, sizeof(addr));
999
+ addr.sin_family = AF_INET;
1000
+ addr.sin_addr = sa->sin_addr;
1001
+ addr.sin_port = htons((unsigned short)port);
1002
+ freeaddrinfo(res);
1003
+ k = sendto(s, (const char *)(MEM + buf), (int)n, 0,
1004
+ (struct sockaddr *)&addr, sizeof(addr));
1005
+ return k < 0 ? (uint64_t)-1 : (uint64_t)k;
1006
+ }
1007
+
1008
+ static uint64_t rt_udp_recvfrom(uint64_t fd, uint64_t buf, uint64_t max,
1009
+ uint64_t srcinfo) {
1010
+ rt_sock_t s = rt_sock_get(fd);
1011
+ struct sockaddr_in from;
1012
+ int fl = (int)sizeof(from);
1013
+ int k;
1014
+ char text[64];
1015
+ size_t tn;
1016
+ if (s == RT_BAD_SOCK || max > (8u << 20)) return (uint64_t)-1;
1017
+ if (buf >= MEMSZ || max > MEMSZ - buf) return (uint64_t)-1;
1018
+ k = recvfrom(s, (char *)(MEM + buf), (int)max, 0,
1019
+ (struct sockaddr *)&from, &fl);
1020
+ if (k < 0) return (uint64_t)-1;
1021
+ if (srcinfo && srcinfo < MEMSZ) {
1022
+ inet_ntop(AF_INET, &from.sin_addr, text, sizeof(text));
1023
+ tn = strlen(text);
1024
+ snprintf(text + tn, sizeof(text) - tn, ":%u",
1025
+ (unsigned)ntohs(from.sin_port));
1026
+ tn = strlen(text);
1027
+ if (srcinfo + tn + 1 <= MEMSZ)
1028
+ memcpy(MEM + srcinfo, text, tn + 1);
1029
+ }
1030
+ return (uint64_t)k;
1031
+ }
1032
+
1033
+ /* ---------------- Base64 (SYS 101/102) ---------------- */
1034
+
1035
+ static const char RT_B64[] =
1036
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1037
+
1038
+ static uint64_t rt_b64enc(uint64_t addr) {
1039
+ const unsigned char *s = (const unsigned char *)rt_cstr(addr);
1040
+ size_t n = strlen((const char *)s);
1041
+ size_t outn = 4 * ((n + 2) / 3);
1042
+ uint64_t p = rt_heap((uint64_t)outn + 1);
1043
+ size_t i, j = 0;
1044
+ if (!p) return 0;
1045
+ for (i = 0; i + 2 < n; i += 3) {
1046
+ unsigned v = ((unsigned)s[i] << 16) | ((unsigned)s[i + 1] << 8)
1047
+ | (unsigned)s[i + 2];
1048
+ MEM[p + j++] = RT_B64[(v >> 18) & 63];
1049
+ MEM[p + j++] = RT_B64[(v >> 12) & 63];
1050
+ MEM[p + j++] = RT_B64[(v >> 6) & 63];
1051
+ MEM[p + j++] = RT_B64[v & 63];
1052
+ }
1053
+ if (i < n) {
1054
+ unsigned v = (unsigned)s[i] << 16;
1055
+ int rem = (int)(n - i);
1056
+ if (rem == 2) v |= (unsigned)s[i + 1] << 8;
1057
+ MEM[p + j++] = RT_B64[(v >> 18) & 63];
1058
+ MEM[p + j++] = RT_B64[(v >> 12) & 63];
1059
+ MEM[p + j++] = rem == 2 ? RT_B64[(v >> 6) & 63] : '=';
1060
+ MEM[p + j++] = '=';
1061
+ }
1062
+ MEM[p + j] = 0;
1063
+ return p;
1064
+ }
1065
+
1066
+ static int rt_b64val(int c) {
1067
+ if (c >= 'A' && c <= 'Z') return c - 'A';
1068
+ if (c >= 'a' && c <= 'z') return c - 'a' + 26;
1069
+ if (c >= '0' && c <= '9') return c - '0' + 52;
1070
+ if (c == '+') return 62;
1071
+ if (c == '/') return 63;
1072
+ return -1;
1073
+ }
1074
+
1075
+ static uint64_t rt_b64dec(uint64_t addr) {
1076
+ const char *s = rt_cstr(addr);
1077
+ size_t n = strlen(s);
1078
+ uint64_t p = rt_heap((uint64_t)(n / 4 + 1) * 3 + 1);
1079
+ size_t i, j = 0;
1080
+ int quad[4], k = 0;
1081
+ if (!p) return 0;
1082
+ for (i = 0; i < n; i++) {
1083
+ int v;
1084
+ if (s[i] == ' ' || s[i] == '\n' || s[i] == '\r' || s[i] == '\t'
1085
+ || s[i] == '=')
1086
+ continue;
1087
+ v = rt_b64val((unsigned char)s[i]);
1088
+ if (v < 0) continue;
1089
+ quad[k++] = v;
1090
+ if (k == 4) {
1091
+ unsigned w = ((unsigned)quad[0] << 18) | ((unsigned)quad[1] << 12)
1092
+ | ((unsigned)quad[2] << 6) | (unsigned)quad[3];
1093
+ MEM[p + j++] = (unsigned char)((w >> 16) & 0xFF);
1094
+ MEM[p + j++] = (unsigned char)((w >> 8) & 0xFF);
1095
+ MEM[p + j++] = (unsigned char)(w & 0xFF);
1096
+ k = 0;
1097
+ }
1098
+ }
1099
+ if (k >= 2) {
1100
+ unsigned w = ((unsigned)quad[0] << 18) | ((unsigned)quad[1] << 12);
1101
+ if (k >= 3) w |= (unsigned)quad[2] << 6;
1102
+ MEM[p + j++] = (unsigned char)((w >> 16) & 0xFF);
1103
+ if (k >= 3) MEM[p + j++] = (unsigned char)((w >> 8) & 0xFF);
1104
+ }
1105
+ MEM[p + j] = 0;
1106
+ return p;
1107
+ }
1108
+
1109
+ /* ---------------- SHA-256 (SYS 100) ---------------- */
1110
+
1111
+ static const uint32_t RT_SHA_K[64] = {
1112
+ 0x428a2f98u, 0x71374491u, 0xb5c0fbcfu, 0xe9b5dba5u, 0x3956c25bu,
1113
+ 0x59f111f1u, 0x923f82a4u, 0xab1c5ed5u, 0xd807aa98u, 0x12835b01u,
1114
+ 0x243185beu, 0x550c7dc3u, 0x72be5d74u, 0x80deb1feu, 0x9bdc06a7u,
1115
+ 0xc19bf174u, 0xe49b69c1u, 0xefbe4786u, 0x0fc19dc6u, 0x240ca1ccu,
1116
+ 0x2de92c6fu, 0x4a7484aau, 0x5cb0a9dcu, 0x76f988dau, 0x983e5152u,
1117
+ 0xa831c66du, 0xb00327c8u, 0xbf597fc7u, 0xc6e00bf3u, 0xd5a79147u,
1118
+ 0x06ca6351u, 0x14292967u, 0x27b70a85u, 0x2e1b2138u, 0x4d2c6dfcu,
1119
+ 0x53380d13u, 0x650a7354u, 0x766a0abbu, 0x81c2c92eu, 0x92722c85u,
1120
+ 0xa2bfe8a1u, 0xa81a664bu, 0xc24b8b70u, 0xc76c51a3u, 0xd192e819u,
1121
+ 0xd6990624u, 0xf40e3585u, 0x106aa070u, 0x19a4c116u, 0x1e376c08u,
1122
+ 0x2748774cu, 0x34b0bcb5u, 0x391c0cb3u, 0x4ed8aa4au, 0x5b9cca4fu,
1123
+ 0x682e6ff3u, 0x748f82eeu, 0x78a5636fu, 0x84c87814u, 0x8cc70208u,
1124
+ 0x90befffau, 0xa4506cebu, 0xbef9a3f7u, 0xc67178f2u
1125
+ };
1126
+
1127
+ typedef struct {
1128
+ uint32_t h[8];
1129
+ uint64_t len;
1130
+ unsigned char buf[64];
1131
+ size_t fill;
1132
+ } rt_sha256_ctx;
1133
+
1134
+ static void rt_sha256_init(rt_sha256_ctx *c) {
1135
+ c->h[0] = 0x6a09e667u; c->h[1] = 0xbb67ae85u;
1136
+ c->h[2] = 0x3c6ef372u; c->h[3] = 0xa54ff53au;
1137
+ c->h[4] = 0x510e527fu; c->h[5] = 0x9b05688cu;
1138
+ c->h[6] = 0x1f83d9abu; c->h[7] = 0x5be0cd19u;
1139
+ c->len = 0;
1140
+ c->fill = 0;
1141
+ }
1142
+
1143
+ static uint32_t rt_rotr32(uint32_t x, int n) {
1144
+ return (x >> n) | (x << (32 - n));
1145
+ }
1146
+
1147
+ static void rt_sha256_block(rt_sha256_ctx *c, const unsigned char *p) {
1148
+ uint32_t w[64], a, b, d, e, f, g, h, t1, t2, cc;
1149
+ int i;
1150
+ for (i = 0; i < 16; i++)
1151
+ w[i] = ((uint32_t)p[i * 4] << 24) | ((uint32_t)p[i * 4 + 1] << 16)
1152
+ | ((uint32_t)p[i * 4 + 2] << 8) | (uint32_t)p[i * 4 + 3];
1153
+ for (i = 16; i < 64; i++) {
1154
+ uint32_t s0 = rt_rotr32(w[i - 15], 7) ^ rt_rotr32(w[i - 15], 18)
1155
+ ^ (w[i - 15] >> 3);
1156
+ uint32_t s1 = rt_rotr32(w[i - 2], 17) ^ rt_rotr32(w[i - 2], 19)
1157
+ ^ (w[i - 2] >> 10);
1158
+ w[i] = w[i - 16] + s0 + w[i - 7] + s1;
1159
+ }
1160
+ a = c->h[0]; b = c->h[1]; cc = c->h[2]; d = c->h[3];
1161
+ e = c->h[4]; f = c->h[5]; g = c->h[6]; h = c->h[7];
1162
+ for (i = 0; i < 64; i++) {
1163
+ uint32_t S1 = rt_rotr32(e, 6) ^ rt_rotr32(e, 11) ^ rt_rotr32(e, 25);
1164
+ uint32_t ch = (e & f) ^ ((~e) & g);
1165
+ uint32_t S0 = rt_rotr32(a, 2) ^ rt_rotr32(a, 13) ^ rt_rotr32(a, 22);
1166
+ uint32_t maj = (a & b) ^ (a & cc) ^ (b & cc);
1167
+ t1 = h + S1 + ch + RT_SHA_K[i] + w[i];
1168
+ t2 = S0 + maj;
1169
+ h = g; g = f; f = e; e = d + t1;
1170
+ d = cc; cc = b; b = a; a = t1 + t2;
1171
+ }
1172
+ c->h[0] += a; c->h[1] += b; c->h[2] += cc; c->h[3] += d;
1173
+ c->h[4] += e; c->h[5] += f; c->h[6] += g; c->h[7] += h;
1174
+ }
1175
+
1176
+ static void rt_sha256_update(rt_sha256_ctx *c, const unsigned char *p,
1177
+ size_t n) {
1178
+ c->len += (uint64_t)n;
1179
+ while (n > 0) {
1180
+ size_t take = 64 - c->fill;
1181
+ if (take > n) take = n;
1182
+ memcpy(c->buf + c->fill, p, take);
1183
+ c->fill += take;
1184
+ p += take;
1185
+ n -= take;
1186
+ if (c->fill == 64) {
1187
+ rt_sha256_block(c, c->buf);
1188
+ c->fill = 0;
1189
+ }
1190
+ }
1191
+ }
1192
+
1193
+ static void rt_sha256_final(rt_sha256_ctx *c, unsigned char out[32]) {
1194
+ uint64_t bits = c->len * 8;
1195
+ unsigned char pad = 0x80;
1196
+ unsigned char zero = 0;
1197
+ int i;
1198
+ rt_sha256_update(c, &pad, 1);
1199
+ while (c->fill != 56) rt_sha256_update(c, &zero, 1);
1200
+ for (i = 7; i >= 0; i--) {
1201
+ unsigned char byte = (unsigned char)((bits >> (i * 8)) & 0xFF);
1202
+ rt_sha256_update(c, &byte, 1);
1203
+ }
1204
+ for (i = 0; i < 8; i++) {
1205
+ out[i * 4] = (unsigned char)(c->h[i] >> 24);
1206
+ out[i * 4 + 1] = (unsigned char)(c->h[i] >> 16);
1207
+ out[i * 4 + 2] = (unsigned char)(c->h[i] >> 8);
1208
+ out[i * 4 + 3] = (unsigned char)c->h[i];
1209
+ }
1210
+ }
1211
+
1212
+ static uint64_t rt_sha256_hex(uint64_t addr) {
1213
+ static const char hexdig[] = "0123456789abcdef";
1214
+ const unsigned char *s = (const unsigned char *)rt_cstr(addr);
1215
+ unsigned char digest[32];
1216
+ rt_sha256_ctx ctx;
1217
+ uint64_t p = rt_heap(65);
1218
+ int i;
1219
+ if (!p) return 0;
1220
+ rt_sha256_init(&ctx);
1221
+ rt_sha256_update(&ctx, s, strlen((const char *)s));
1222
+ rt_sha256_final(&ctx, digest);
1223
+ for (i = 0; i < 32; i++) {
1224
+ MEM[p + i * 2] = (unsigned char)hexdig[digest[i] >> 4];
1225
+ MEM[p + i * 2 + 1] = (unsigned char)hexdig[digest[i] & 15];
1226
+ }
1227
+ MEM[p + 64] = 0;
1228
+ return p;
1229
+ }
1230
+
1231
+ /* ---------------- 画布 + PNG (SYS 43-49) ---------------- */
1232
+
1233
+ static unsigned char *CANVAS;
1234
+ static int CW, CH;
1235
+ static int COL_R, COL_G, COL_B;
1236
+
1237
+ static int rt_clamp_coord(uint64_t v) {
1238
+ return v > 100000 ? 100000 : (int)v;
1239
+ }
1240
+
1241
+ static uint64_t rt_canvas_new(uint64_t w, uint64_t h) {
1242
+ int cw = rt_clamp_coord(w), ch = rt_clamp_coord(h);
1243
+ if (cw < 1) cw = 1;
1244
+ if (ch < 1) ch = 1;
1245
+ free(CANVAS);
1246
+ CANVAS = (unsigned char *)malloc((size_t)cw * (size_t)ch * 4);
1247
+ if (!CANVAS) { CW = CH = 0; return (uint64_t)-1; }
1248
+ memset(CANVAS, 255, (size_t)cw * (size_t)ch * 4);
1249
+ CW = cw; CH = ch;
1250
+ COL_R = COL_G = COL_B = 0;
1251
+ return 0;
1252
+ }
1253
+
1254
+ static uint64_t rt_canvas_set(uint64_t rgb) {
1255
+ COL_R = (int)((rgb >> 16) & 0xFF);
1256
+ COL_G = (int)((rgb >> 8) & 0xFF);
1257
+ COL_B = (int)(rgb & 0xFF);
1258
+ return 0;
1259
+ }
1260
+
1261
+ static uint64_t rt_canvas_rect(uint64_t x, uint64_t y, uint64_t w,
1262
+ uint64_t h) {
1263
+ int x0 = rt_clamp_coord(x), y0 = rt_clamp_coord(y);
1264
+ int x1 = x0 + rt_clamp_coord(w), y1 = y0 + rt_clamp_coord(h);
1265
+ int px, py;
1266
+ if (!CANVAS) return (uint64_t)-1;
1267
+ if (x0 < 0) x0 = 0;
1268
+ if (y0 < 0) y0 = 0;
1269
+ if (x1 > CW) x1 = CW;
1270
+ if (y1 > CH) y1 = CH;
1271
+ for (py = y0; py < y1; py++) {
1272
+ for (px = x0; px < x1; px++) {
1273
+ unsigned char *p = CANVAS + ((size_t)py * CW + px) * 4;
1274
+ p[0] = (unsigned char)COL_R;
1275
+ p[1] = (unsigned char)COL_G;
1276
+ p[2] = (unsigned char)COL_B;
1277
+ p[3] = 255;
1278
+ }
1279
+ }
1280
+ return 0;
1281
+ }
1282
+
1283
+ static uint64_t rt_canvas_circle(uint64_t cx, uint64_t cy, uint64_t r) {
1284
+ int x0 = rt_clamp_coord(cx), y0 = rt_clamp_coord(cy);
1285
+ int rr = rt_clamp_coord(r);
1286
+ long dx, dy;
1287
+ if (!CANVAS) return (uint64_t)-1;
1288
+ for (dy = -rr; dy <= rr; dy++) {
1289
+ for (dx = -rr; dx <= rr; dx++) {
1290
+ long px = x0 + dx, py = y0 + dy;
1291
+ if (dx * dx + dy * dy > (long)rr * (long)rr) continue;
1292
+ if (px < 0 || px >= CW || py < 0 || py >= CH) continue;
1293
+ {
1294
+ unsigned char *p = CANVAS + ((size_t)py * CW + px) * 4;
1295
+ p[0] = (unsigned char)COL_R;
1296
+ p[1] = (unsigned char)COL_G;
1297
+ p[2] = (unsigned char)COL_B;
1298
+ p[3] = 255;
1299
+ }
1300
+ }
1301
+ }
1302
+ return 0;
1303
+ }
1304
+
1305
+ static uint64_t rt_canvas_line(uint64_t x0, uint64_t y0, uint64_t x1,
1306
+ uint64_t y1) {
1307
+ long ax = (long)rt_clamp_coord(x0), ay = (long)rt_clamp_coord(y0);
1308
+ long bx = (long)rt_clamp_coord(x1), by = (long)rt_clamp_coord(y1);
1309
+ long dx = labs(bx - ax), sx = ax < bx ? 1 : -1;
1310
+ long dy = -labs(by - ay), sy = ay < by ? 1 : -1;
1311
+ long err = dx + dy;
1312
+ if (!CANVAS) return (uint64_t)-1;
1313
+ for (;;) {
1314
+ if (ax >= 0 && ax < CW && ay >= 0 && ay < CH) {
1315
+ unsigned char *p = CANVAS + ((size_t)ay * CW + ax) * 4;
1316
+ p[0] = (unsigned char)COL_R;
1317
+ p[1] = (unsigned char)COL_G;
1318
+ p[2] = (unsigned char)COL_B;
1319
+ p[3] = 255;
1320
+ }
1321
+ if (ax == bx && ay == by) break;
1322
+ {
1323
+ long e2 = 2 * err;
1324
+ if (e2 >= dy) { err += dy; ax += sx; }
1325
+ if (e2 <= dx) { err += dx; ay += sy; }
1326
+ }
1327
+ }
1328
+ return 0;
1329
+ }
1330
+
1331
+ /* 内置 5x7 点阵字库 (ASCII 32..126; 小写映射为大写, 缺失字符用 '?')。 */
1332
+ static const unsigned char FONT5X7[95][7] = {
1333
+ {0,0,0,0,0,0,0}, {4,4,4,4,4,0,4}, {14,17,1,2,4,0,4}, {14,17,1,2,4,0,4},
1334
+ {14,17,1,2,4,0,4}, {14,17,1,2,4,0,4}, {14,17,1,2,4,0,4}, {14,17,1,2,4,0,4},
1335
+ {14,17,1,2,4,0,4}, {14,17,1,2,4,0,4}, {14,17,1,2,4,0,4}, {14,17,1,2,4,0,4},
1336
+ {0,0,0,0,6,4,8}, {0,0,0,31,0,0,0}, {0,0,0,0,0,12,12}, {1,1,2,4,8,16,16},
1337
+ {14,17,19,21,25,17,14}, {4,12,4,4,4,4,14}, {14,17,1,2,4,8,31}, {31,1,2,6,1,17,14},
1338
+ {2,6,10,18,31,2,2}, {31,16,30,1,1,17,14}, {6,8,16,30,17,17,14}, {31,1,2,4,8,8,8},
1339
+ {14,17,17,14,17,17,14}, {14,17,17,15,1,2,12}, {0,6,6,0,6,6,0}, {14,17,1,2,4,0,4},
1340
+ {14,17,1,2,4,0,4}, {14,17,1,2,4,0,4}, {14,17,1,2,4,0,4}, {14,17,1,2,4,0,4},
1341
+ {14,17,1,2,4,0,4}, {14,17,17,31,17,17,17}, {30,17,17,30,17,17,30}, {14,17,16,16,16,17,14},
1342
+ {30,17,17,17,17,17,30}, {31,16,16,30,16,16,31}, {31,16,16,30,16,16,16}, {14,17,16,23,17,17,15},
1343
+ {17,17,17,31,17,17,17}, {14,4,4,4,4,4,14}, {1,1,1,1,17,17,14}, {17,18,20,24,20,18,17},
1344
+ {16,16,16,16,16,16,31}, {17,27,21,21,17,17,17}, {17,25,21,19,17,17,17}, {14,17,17,17,17,17,14},
1345
+ {30,17,17,30,16,16,16}, {14,17,17,17,21,18,13}, {30,17,17,30,20,18,17}, {15,16,16,14,1,1,30},
1346
+ {31,4,4,4,4,4,4}, {17,17,17,17,17,17,14}, {17,17,17,17,17,10,4}, {17,17,17,21,21,27,17},
1347
+ {17,17,10,4,10,17,17}, {17,17,10,4,4,4,4}, {31,1,2,4,8,16,31}, {14,17,1,2,4,0,4},
1348
+ {14,17,1,2,4,0,4}, {14,17,1,2,4,0,4}, {14,17,1,2,4,0,4}, {14,17,1,2,4,0,4},
1349
+ {14,17,1,2,4,0,4}, {14,17,17,31,17,17,17}, {30,17,17,30,17,17,30}, {14,17,16,16,16,17,14},
1350
+ {30,17,17,17,17,17,30}, {31,16,16,30,16,16,31}, {31,16,16,30,16,16,16}, {14,17,16,23,17,17,15},
1351
+ {17,17,17,31,17,17,17}, {14,4,4,4,4,4,14}, {1,1,1,1,17,17,14}, {17,18,20,24,20,18,17},
1352
+ {16,16,16,16,16,16,31}, {17,27,21,21,17,17,17}, {17,25,21,19,17,17,17}, {14,17,17,17,17,17,14},
1353
+ {30,17,17,30,16,16,16}, {14,17,17,17,21,18,13}, {30,17,17,30,20,18,17}, {15,16,16,14,1,1,30},
1354
+ {31,4,4,4,4,4,4}, {17,17,17,17,17,17,14}, {17,17,17,17,17,10,4}, {17,17,17,21,21,27,17},
1355
+ {17,17,10,4,10,17,17}, {17,17,10,4,4,4,4}, {31,1,2,4,8,16,31}, {14,17,1,2,4,0,4},
1356
+ {14,17,1,2,4,0,4}, {14,17,1,2,4,0,4}, {14,17,1,2,4,0,4},
1357
+ };
1358
+
1359
+ static const unsigned char *rt_font_glyph(int ch) {
1360
+ if (ch >= 'a' && ch <= 'z') ch = ch - 'a' + 'A';
1361
+ if (ch < 32 || ch > 126) ch = '?';
1362
+ return FONT5X7[ch - 32];
1363
+ }
1364
+
1365
+ static uint64_t rt_canvas_text(uint64_t x, uint64_t y, uint64_t addr) {
1366
+ const char *s;
1367
+ int ox, oy, px;
1368
+ if (!CANVAS) return (uint64_t)-1;
1369
+ ox = rt_clamp_coord(x);
1370
+ oy = rt_clamp_coord(y);
1371
+ s = rt_cstr(addr);
1372
+ px = ox;
1373
+ while (s && *s) {
1374
+ const unsigned char *g = rt_font_glyph((unsigned char)*s++);
1375
+ int row, col;
1376
+ for (row = 0; row < 7; row++) {
1377
+ unsigned char bits = g[row];
1378
+ for (col = 0; col < 5; col++) {
1379
+ if (bits & (1u << (4 - col))) {
1380
+ int cx = px + col, cy = oy + row;
1381
+ if (cx >= 0 && cx < CW && cy >= 0 && cy < CH) {
1382
+ unsigned char *p = CANVAS + ((size_t)cy * CW + cx) * 4;
1383
+ p[0] = (unsigned char)COL_R;
1384
+ p[1] = (unsigned char)COL_G;
1385
+ p[2] = (unsigned char)COL_B;
1386
+ p[3] = 255;
1387
+ }
1388
+ }
1389
+ }
1390
+ }
1391
+ px += 6;
1392
+ }
1393
+ return 0;
1394
+ }
1395
+
1396
+ static uint32_t rt_crc32(const unsigned char *data, size_t n) {
1397
+ uint32_t crc = 0xFFFFFFFFu;
1398
+ size_t i;
1399
+ int k;
1400
+ for (i = 0; i < n; i++) {
1401
+ crc ^= data[i];
1402
+ for (k = 0; k < 8; k++)
1403
+ crc = (crc >> 1) ^ (0xEDB88320u & (uint32_t)(-(int32_t)(crc & 1)));
1404
+ }
1405
+ return crc ^ 0xFFFFFFFFu;
1406
+ }
1407
+
1408
+ static void rt_png_chunk(FILE *f, const char *type, const unsigned char *data,
1409
+ size_t n) {
1410
+ unsigned char hdr[8];
1411
+ unsigned char crcbuf[4];
1412
+ uint32_t crc;
1413
+ unsigned char *tmp = (unsigned char *)malloc(n + 4);
1414
+ hdr[0] = (unsigned char)(n >> 24); hdr[1] = (unsigned char)(n >> 16);
1415
+ hdr[2] = (unsigned char)(n >> 8); hdr[3] = (unsigned char)n;
1416
+ memcpy(hdr + 4, type, 4);
1417
+ fwrite(hdr, 1, 8, f);
1418
+ if (n) fwrite(data, 1, n, f);
1419
+ if (!tmp) return;
1420
+ memcpy(tmp, type, 4);
1421
+ if (n) memcpy(tmp + 4, data, n);
1422
+ crc = rt_crc32(tmp, n + 4);
1423
+ crcbuf[0] = (unsigned char)(crc >> 24); crcbuf[1] = (unsigned char)(crc >> 16);
1424
+ crcbuf[2] = (unsigned char)(crc >> 8); crcbuf[3] = (unsigned char)crc;
1425
+ fwrite(crcbuf, 1, 4, f);
1426
+ free(tmp);
1427
+ }
1428
+
1429
+ static uint64_t rt_canvas_save(const char *path) {
1430
+ FILE *f;
1431
+ unsigned char ihdr[13];
1432
+ unsigned char *raw = NULL, *z = NULL;
1433
+ size_t rown = (size_t)CW * 4 + 1, rawlen, zlen, off = 0, i, left;
1434
+ uint32_t a = 1, b = 0;
1435
+ int y;
1436
+ if (!CANVAS || !path || !*path) return (uint64_t)-1;
1437
+ rawlen = rown * (size_t)CH;
1438
+ raw = (unsigned char *)malloc(rawlen);
1439
+ if (!raw) return (uint64_t)-1;
1440
+ for (y = 0; y < CH; y++) {
1441
+ raw[(size_t)y * rown] = 0; /* filter: none */
1442
+ memcpy(raw + (size_t)y * rown + 1, CANVAS + (size_t)y * CW * 4,
1443
+ (size_t)CW * 4);
1444
+ }
1445
+ /* zlib: 2 字节头 + stored deflate 块 + adler32 */
1446
+ zlen = rawlen + rawlen / 65535 * 5 + 64;
1447
+ z = (unsigned char *)malloc(zlen);
1448
+ if (!z) { free(raw); return (uint64_t)-1; }
1449
+ z[off++] = 0x78; z[off++] = 0x01;
1450
+ left = rawlen;
1451
+ i = 0;
1452
+ while (i < rawlen) {
1453
+ size_t blk = left > 65535 ? 65535 : left;
1454
+ int final = (i + blk >= rawlen);
1455
+ z[off++] = (unsigned char)(final ? 1 : 0);
1456
+ z[off++] = (unsigned char)(blk & 0xFF);
1457
+ z[off++] = (unsigned char)((blk >> 8) & 0xFF);
1458
+ z[off++] = (unsigned char)(~blk & 0xFF);
1459
+ z[off++] = (unsigned char)((~blk >> 8) & 0xFF);
1460
+ memcpy(z + off, raw + i, blk);
1461
+ off += blk;
1462
+ i += blk;
1463
+ left -= blk;
1464
+ }
1465
+ for (i = 0; i < rawlen; i++) {
1466
+ a = (a + raw[i]) % 65521u;
1467
+ b = (b + a) % 65521u;
1468
+ }
1469
+ {
1470
+ uint32_t adler = (b << 16) | a;
1471
+ z[off++] = (unsigned char)(adler >> 24);
1472
+ z[off++] = (unsigned char)(adler >> 16);
1473
+ z[off++] = (unsigned char)(adler >> 8);
1474
+ z[off++] = (unsigned char)adler;
1475
+ }
1476
+ f = fopen(path, "wb");
1477
+ if (!f) { free(raw); free(z); return (uint64_t)-1; }
1478
+ fwrite("\x89PNG\r\n\x1a\n", 1, 8, f);
1479
+ ihdr[0] = (unsigned char)(CW >> 24); ihdr[1] = (unsigned char)(CW >> 16);
1480
+ ihdr[2] = (unsigned char)(CW >> 8); ihdr[3] = (unsigned char)CW;
1481
+ ihdr[4] = (unsigned char)(CH >> 24); ihdr[5] = (unsigned char)(CH >> 16);
1482
+ ihdr[6] = (unsigned char)(CH >> 8); ihdr[7] = (unsigned char)CH;
1483
+ ihdr[8] = 8; ihdr[9] = 6; ihdr[10] = 0; ihdr[11] = 0; ihdr[12] = 0;
1484
+ rt_png_chunk(f, "IHDR", ihdr, 13);
1485
+ rt_png_chunk(f, "IDAT", z, off);
1486
+ rt_png_chunk(f, "IEND", NULL, 0);
1487
+ fclose(f);
1488
+ free(raw);
1489
+ free(z);
1490
+ return 0;
1491
+ }
1492
+
1493
+ static uint64_t rt_download(uint64_t url, uint64_t path) {
1494
+ uint64_t body = rt_http("GET", rt_cstr(url), "", "");
1495
+ if (ERRMSG) return (uint64_t)-1;
1496
+ if (LASTHTTPST < 200 || LASTHTTPST >= 300) return (uint64_t)-1;
1497
+ return rt_writefile(rt_cstr(path), rt_cstr(body), 0) == 0
1498
+ ? 0 : (uint64_t)-1;
1499
+ }
1500
+
1501
+ static uint64_t rt_is_dir(const char *path) {
1502
+ struct stat st;
1503
+ return (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) ? 1 : 0;
1504
+ }
1505
+
1506
+ static uint64_t rt_chdir(const char *path) {
1507
+ #ifdef _WIN32
1508
+ return _chdir(path) == 0 ? 0 : (uint64_t)-1;
1509
+ #else
1510
+ return chdir(path) == 0 ? 0 : (uint64_t)-1;
1511
+ #endif
1512
+ }
1513
+
1514
+ static uint64_t rt_temp_dir(void) {
1515
+ static const char *keys[] = {"TMPDIR", "TEMP", "TMP"};
1516
+ size_t i;
1517
+ for (i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
1518
+ const char *v = getenv(keys[i]);
1519
+ if (v && *v) return rt_dupstr(v);
1520
+ }
1521
+ return rt_dupstr("/tmp");
1522
+ }
1523
+
1524
+ static int rt_rm_rf(const char *path) {
1525
+ struct stat st;
1526
+ if (stat(path, &st) != 0) return -1;
1527
+ if (S_ISDIR(st.st_mode)) {
1528
+ DIR *d = opendir(path);
1529
+ struct dirent *ent;
1530
+ if (!d) return -1;
1531
+ while ((ent = readdir(d)) != NULL) {
1532
+ char child[2048];
1533
+ if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
1534
+ continue;
1535
+ snprintf(child, sizeof(child), "%s/%s", path, ent->d_name);
1536
+ if (rt_rm_rf(child) != 0) {
1537
+ closedir(d);
1538
+ return -1;
1539
+ }
1540
+ }
1541
+ closedir(d);
1542
+ #ifdef _WIN32
1543
+ return _rmdir(path);
1544
+ #else
1545
+ return rmdir(path);
1546
+ #endif
1547
+ }
1548
+ return remove(path);
1549
+ }
1550
+
1551
+ static uint64_t rt_dir_remove(const char *path) {
1552
+ return rt_rm_rf(path) == 0 ? 0 : (uint64_t)-1;
1553
+ }
1554
+
1555
+ static uint64_t rt_file_copy(const char *src, const char *dst) {
1556
+ FILE *in = fopen(src, "rb");
1557
+ FILE *out;
1558
+ char buf[8192];
1559
+ size_t n;
1560
+ int ok = 1;
1561
+ if (!in) return (uint64_t)-1;
1562
+ out = fopen(dst, "wb");
1563
+ if (!out) { fclose(in); return (uint64_t)-1; }
1564
+ while ((n = fread(buf, 1, sizeof(buf), in)) > 0) {
1565
+ if (fwrite(buf, 1, n, out) != n) { ok = 0; break; }
1566
+ }
1567
+ fclose(in);
1568
+ if (fclose(out) != 0) ok = 0;
1569
+ return ok ? 0 : (uint64_t)-1;
1570
+ }
1571
+
1572
+ static uint64_t rt_file_move(const char *src, const char *dst) {
1573
+ if (rename(src, dst) == 0) return 0;
1574
+ if (rt_file_copy(src, dst) != 0) return (uint64_t)-1;
1575
+ return remove(src) == 0 ? 0 : (uint64_t)-1;
1576
+ }
1577
+
1578
+ static uint64_t rt_file_mtime(const char *path) {
1579
+ struct stat st;
1580
+ if (stat(path, &st) != 0) return (uint64_t)-1;
1581
+ return (uint64_t)st.st_mtime;
1582
+ }
1583
+
1584
+ #ifdef _WIN32
1585
+ #define RT_SEP '\\'
1586
+ #else
1587
+ #define RT_SEP '/'
1588
+ #endif
1589
+
1590
+ static int rt_is_sep(int c) { return c == '/' || c == '\\'; }
1591
+
1592
+ static void rt_norm_seps(char *s) {
1593
+ char *w = s;
1594
+ int last_sep = 0;
1595
+ for (; *s; s++) {
1596
+ if (rt_is_sep((unsigned char)*s)) {
1597
+ if (last_sep) continue;
1598
+ *w++ = RT_SEP;
1599
+ last_sep = 1;
1600
+ } else {
1601
+ *w++ = *s;
1602
+ last_sep = 0;
1603
+ }
1604
+ }
1605
+ *w = 0;
1606
+ }
1607
+
1608
+ static uint64_t rt_path_join(const char *a, const char *b) {
1609
+ char buf[2048];
1610
+ if (!b || !*b) return rt_dupstr(a ? a : "");
1611
+ if (b[0] == '/' || b[0] == '\\' || (b[0] && b[1] == ':'))
1612
+ return rt_dupstr(b);
1613
+ snprintf(buf, sizeof(buf), "%s%c%s", a ? a : "", RT_SEP, b);
1614
+ rt_norm_seps(buf);
1615
+ return rt_dupstr(buf);
1616
+ }
1617
+
1618
+ static uint64_t rt_path_basename(const char *p) {
1619
+ const char *end = p + strlen(p), *start = p;
1620
+ while (end > p && rt_is_sep((unsigned char)end[-1])) end--;
1621
+ start = end;
1622
+ while (start > p && !rt_is_sep((unsigned char)start[-1])) start--;
1623
+ {
1624
+ size_t n = (size_t)(end - start);
1625
+ char buf[2048];
1626
+ if (n >= sizeof(buf)) n = sizeof(buf) - 1;
1627
+ memcpy(buf, start, n);
1628
+ buf[n] = 0;
1629
+ return rt_dupstr(buf);
1630
+ }
1631
+ }
1632
+
1633
+ static uint64_t rt_path_dirname(const char *p) {
1634
+ char buf[2048];
1635
+ size_t n = strlen(p);
1636
+ while (n > 1 && rt_is_sep((unsigned char)p[n - 1])) n--;
1637
+ while (n > 0 && !rt_is_sep((unsigned char)p[n - 1])) n--;
1638
+ while (n > 1 && rt_is_sep((unsigned char)p[n - 1])) n--;
1639
+ if (n == 0) return rt_dupstr(".");
1640
+ if (n >= sizeof(buf)) n = sizeof(buf) - 1;
1641
+ memcpy(buf, p, n);
1642
+ buf[n] = 0;
1643
+ rt_norm_seps(buf);
1644
+ return rt_dupstr(buf);
1645
+ }
1646
+
1647
+ static uint64_t rt_path_abs(const char *p) {
1648
+ char buf[4096];
1649
+ #ifdef _WIN32
1650
+ if (!_fullpath(buf, p, sizeof(buf))) return rt_empty();
1651
+ #else
1652
+ if (!realpath(p, buf)) {
1653
+ char cwd[2048];
1654
+ if (!getcwd(cwd, sizeof(cwd))) return rt_empty();
1655
+ if (p[0] == '/') return rt_dupstr(p);
1656
+ snprintf(buf, sizeof(buf), "%s/%s", cwd, p);
1657
+ }
1658
+ #endif
1659
+ rt_norm_seps(buf);
1660
+ return rt_dupstr(buf);
1661
+ }
1662
+
1663
+ static uint64_t rt_time_ms(void) {
1664
+ #ifdef _WIN32
1665
+ return (uint64_t)GetTickCount64();
1666
+ #else
1667
+ struct timespec ts;
1668
+ clock_gettime(CLOCK_MONOTONIC, &ts);
1669
+ return (uint64_t)ts.tv_sec * 1000u + (uint64_t)ts.tv_nsec / 1000000u;
1670
+ #endif
1671
+ }
1672
+
1673
+ static uint64_t rt_sleep_ms(uint64_t ms) {
1674
+ if (ms > 600000) ms = 600000;
1675
+ #ifdef _WIN32
1676
+ Sleep((DWORD)ms);
1677
+ #else
1678
+ {
1679
+ struct timespec ts;
1680
+ ts.tv_sec = (time_t)(ms / 1000);
1681
+ ts.tv_nsec = (long)((ms % 1000) * 1000000);
1682
+ nanosleep(&ts, NULL);
1683
+ }
1684
+ #endif
1685
+ return 0;
1686
+ }
1687
+
1688
+ static uint64_t rt_cpu_count(void) {
1689
+ #ifdef _WIN32
1690
+ SYSTEM_INFO si;
1691
+ GetSystemInfo(&si);
1692
+ return (uint64_t)si.dwNumberOfProcessors;
1693
+ #else
1694
+ long n = sysconf(_SC_NPROCESSORS_ONLN);
1695
+ return n > 0 ? (uint64_t)n : 1;
1696
+ #endif
1697
+ }
1698
+
1699
+ static uint64_t rt_arch_name(void) {
1700
+ #if defined(__aarch64__) || defined(_M_ARM64)
1701
+ return rt_dupstr("arm64");
1702
+ #elif defined(__x86_64__) || defined(_M_X64)
1703
+ return rt_dupstr("amd64");
1704
+ #else
1705
+ return rt_dupstr("x86");
1706
+ #endif
1707
+ }
1708
+
1709
+ static uint64_t rt_meminfo(void) {
1710
+ char buf[160];
1711
+ #ifdef _WIN32
1712
+ MEMORYSTATUSEX ms;
1713
+ ms.dwLength = sizeof(ms);
1714
+ if (GlobalMemoryStatusEx(&ms)) {
1715
+ snprintf(buf, sizeof(buf), "{\"total_kb\":%llu,\"free_kb\":%llu}",
1716
+ (unsigned long long)(ms.ullTotalPhys / 1024),
1717
+ (unsigned long long)(ms.ullAvailPhys / 1024));
1718
+ return rt_dupstr(buf);
1719
+ }
1720
+ #else
1721
+ {
1722
+ FILE *f = fopen("/proc/meminfo", "rb");
1723
+ unsigned long long total = 0, avail = 0;
1724
+ char line[256];
1725
+ if (f) {
1726
+ while (fgets(line, sizeof(line), f)) {
1727
+ if (!total && sscanf(line, "MemTotal: %llu kB", &total) == 1)
1728
+ continue;
1729
+ if (!avail &&
1730
+ sscanf(line, "MemAvailable: %llu kB", &avail) == 1)
1731
+ continue;
1732
+ }
1733
+ fclose(f);
1734
+ }
1735
+ snprintf(buf, sizeof(buf), "{\"total_kb\":%llu,\"free_kb\":%llu}",
1736
+ total, avail);
1737
+ return rt_dupstr(buf);
1738
+ }
1739
+ #endif
1740
+ return rt_dupstr("{\"total_kb\":0,\"free_kb\":0}");
1741
+ }
1742
+
1743
+ static uint64_t rt_is_android(void) {
1744
+ struct stat st;
1745
+ return stat("/system/build.prop", &st) == 0 ? 1 : 0;
1746
+ }
1747
+
1748
+ /* ---------------- 进程执行 (SYS 59/60) ---------------- */
1749
+
1750
+ #ifdef _WIN32
1751
+ #define rt_popen _popen
1752
+ #define rt_pclose _pclose
1753
+ #else
1754
+ #define rt_popen popen
1755
+ #define rt_pclose pclose
1756
+ #endif
1757
+
1758
+ static uint64_t rt_exec_cmd(const char *cmd) {
1759
+ int status = system(cmd);
1760
+ if (status == -1) return (uint64_t)-1;
1761
+ #ifdef _WIN32
1762
+ return (uint64_t)status;
1763
+ #else
1764
+ if (WIFEXITED(status)) return (uint64_t)WEXITSTATUS(status);
1765
+ return (uint64_t)-1; /* 被信号终止: Go 侧 ExitCode() 同样返回 -1 */
1766
+ #endif
1767
+ }
1768
+
1769
+ static uint64_t rt_exec_output(const char *cmd) {
1770
+ FILE *p = rt_popen(cmd, "r");
1771
+ char *buf = NULL;
1772
+ size_t cap = 0, len = 0, n;
1773
+ uint64_t result;
1774
+ if (!p) return rt_empty();
1775
+ for (;;) {
1776
+ if (len + 4096 + 1 > cap) {
1777
+ size_t ncap = cap ? cap * 2 : 8192;
1778
+ char *nb;
1779
+ while (ncap < len + 4096 + 1) ncap *= 2;
1780
+ nb = (char *)realloc(buf, ncap);
1781
+ if (!nb) break;
1782
+ buf = nb;
1783
+ cap = ncap;
1784
+ }
1785
+ n = fread(buf + len, 1, cap - len - 1, p);
1786
+ if (n == 0) break;
1787
+ len += n;
1788
+ }
1789
+ rt_pclose(p);
1790
+ if (!buf) return rt_empty();
1791
+ buf[len] = 0;
1792
+ result = rt_dupstr(buf);
1793
+ free(buf);
1794
+ return result;
1795
+ }
1796
+
1797
+ /* ---------------- 桌面集成 (SYS 103-106) ---------------- */
1798
+
1799
+ static void rt_shell_sq(const char *in, char *out, size_t cap) {
1800
+ size_t o = 0;
1801
+ for (; *in && o + 5 < cap; in++) {
1802
+ if (*in == '\'') {
1803
+ out[o++] = '\'';
1804
+ out[o++] = '\\';
1805
+ out[o++] = '\'';
1806
+ out[o++] = '\'';
1807
+ } else {
1808
+ out[o++] = *in;
1809
+ }
1810
+ }
1811
+ out[o] = 0;
1812
+ }
1813
+
1814
+ #ifdef _WIN32
1815
+ static void rt_ps_sq(const char *in, char *out, size_t cap) {
1816
+ size_t o = 0;
1817
+ for (; *in && o + 3 < cap; in++) {
1818
+ if (*in == '\'') out[o++] = '\'';
1819
+ out[o++] = *in;
1820
+ }
1821
+ out[o] = 0;
1822
+ }
1823
+
1824
+ static void rt_win_dq(const char *in, char *out, size_t cap) {
1825
+ size_t o = 0;
1826
+ for (; *in && o + 3 < cap; in++) {
1827
+ if (*in == '"') { out[o++] = '"'; out[o++] = '"'; }
1828
+ else out[o++] = *in;
1829
+ }
1830
+ out[o] = 0;
1831
+ }
1832
+
1833
+ static uint64_t rt_clip_get(void) {
1834
+ HANDLE h;
1835
+ char *utf8 = NULL;
1836
+ wchar_t *w;
1837
+ int n;
1838
+ if (!OpenClipboard(NULL)) return rt_empty();
1839
+ h = GetClipboardData(CF_UNICODETEXT);
1840
+ if (h) {
1841
+ w = (wchar_t *)GlobalLock(h);
1842
+ if (w) {
1843
+ n = WideCharToMultiByte(CP_UTF8, 0, w, -1, NULL, 0, NULL, NULL);
1844
+ if (n > 0) utf8 = (char *)malloc((size_t)n);
1845
+ if (utf8) WideCharToMultiByte(CP_UTF8, 0, w, -1, utf8, n, NULL,
1846
+ NULL);
1847
+ GlobalUnlock(h);
1848
+ }
1849
+ CloseClipboard();
1850
+ } else {
1851
+ CloseClipboard();
1852
+ }
1853
+ if (utf8) {
1854
+ size_t len = strlen(utf8);
1855
+ uint64_t r;
1856
+ while (len > 0 && (utf8[len - 1] == '\r' || utf8[len - 1] == '\n'))
1857
+ utf8[--len] = 0;
1858
+ r = rt_dupstr(utf8);
1859
+ free(utf8);
1860
+ return r;
1861
+ }
1862
+ return rt_empty();
1863
+ }
1864
+
1865
+ static uint64_t rt_clip_set(const char *text) {
1866
+ int n = MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
1867
+ HGLOBAL mem;
1868
+ wchar_t *dst;
1869
+ if (n <= 0) return (uint64_t)-1;
1870
+ mem = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)n * sizeof(wchar_t));
1871
+ if (!mem) return (uint64_t)-1;
1872
+ dst = (wchar_t *)GlobalLock(mem);
1873
+ if (!dst) { GlobalFree(mem); return (uint64_t)-1; }
1874
+ MultiByteToWideChar(CP_UTF8, 0, text, -1, dst, n);
1875
+ GlobalUnlock(mem);
1876
+ if (!OpenClipboard(NULL)) { GlobalFree(mem); return (uint64_t)-1; }
1877
+ EmptyClipboard();
1878
+ if (!SetClipboardData(CF_UNICODETEXT, mem)) {
1879
+ CloseClipboard();
1880
+ GlobalFree(mem);
1881
+ return (uint64_t)-1;
1882
+ }
1883
+ CloseClipboard();
1884
+ return 0;
1885
+ }
1886
+ #else
1887
+ static uint64_t rt_clip_get(void) {
1888
+ static const char *cmds[] = {
1889
+ "wl-paste --no-newline 2>/dev/null",
1890
+ "xclip -selection clipboard -o 2>/dev/null",
1891
+ "xsel -b 2>/dev/null",
1892
+ };
1893
+ size_t ci;
1894
+ for (ci = 0; ci < sizeof(cmds) / sizeof(cmds[0]); ci++) {
1895
+ FILE *p = popen(cmds[ci], "r");
1896
+ char *buf = NULL;
1897
+ size_t cap = 0, len = 0, n;
1898
+ int rc;
1899
+ if (!p) continue;
1900
+ for (;;) {
1901
+ if (len + 4096 + 1 > cap) {
1902
+ size_t ncap = cap ? cap * 2 : 8192;
1903
+ char *nb;
1904
+ while (ncap < len + 4096 + 1) ncap *= 2;
1905
+ nb = (char *)realloc(buf, ncap);
1906
+ if (!nb) break;
1907
+ buf = nb;
1908
+ cap = ncap;
1909
+ }
1910
+ n = fread(buf + len, 1, cap - len - 1, p);
1911
+ if (n == 0) break;
1912
+ len += n;
1913
+ }
1914
+ rc = pclose(p);
1915
+ if (rc == 0 && buf && len > 0) {
1916
+ uint64_t r;
1917
+ while (len > 0 && (buf[len - 1] == '\r' || buf[len - 1] == '\n'))
1918
+ buf[--len] = 0;
1919
+ r = rt_dupstr(buf);
1920
+ free(buf);
1921
+ return r;
1922
+ }
1923
+ free(buf);
1924
+ }
1925
+ return rt_empty();
1926
+ }
1927
+
1928
+ static uint64_t rt_clip_set(const char *text) {
1929
+ static const char *cmds[] = {
1930
+ "wl-copy 2>/dev/null",
1931
+ "xclip -selection clipboard -i 2>/dev/null",
1932
+ "xsel -b -i 2>/dev/null",
1933
+ };
1934
+ size_t ci;
1935
+ for (ci = 0; ci < sizeof(cmds) / sizeof(cmds[0]); ci++) {
1936
+ FILE *p = popen(cmds[ci], "w");
1937
+ if (!p) continue;
1938
+ fwrite(text, 1, strlen(text), p);
1939
+ if (pclose(p) == 0) return 0;
1940
+ }
1941
+ return (uint64_t)-1;
1942
+ }
1943
+ #endif
1944
+
1945
+ static uint64_t rt_notify(const char *title, const char *body) {
1946
+ char cmd[4096];
1947
+ #ifdef _WIN32
1948
+ char t[1024], b[2048];
1949
+ rt_ps_sq(title, t, sizeof(t));
1950
+ rt_ps_sq(body, b, sizeof(b));
1951
+ snprintf(cmd, sizeof(cmd),
1952
+ "powershell -NoProfile -Command \"(New-Object -ComObject "
1953
+ "Wscript.Shell).Popup('%s',10,'%s',64)\"", b, t);
1954
+ #else
1955
+ char t[1024], b[2048];
1956
+ rt_shell_sq(title, t, sizeof(t));
1957
+ rt_shell_sq(body, b, sizeof(b));
1958
+ #ifdef __APPLE__
1959
+ snprintf(cmd, sizeof(cmd),
1960
+ "osascript -e 'display notification \"%s\" with title \"%s\"'",
1961
+ b, t);
1962
+ #else
1963
+ snprintf(cmd, sizeof(cmd), "notify-send '%s' '%s'", t, b);
1964
+ #endif
1965
+ #endif
1966
+ return system(cmd) == 0 ? 0 : (uint64_t)-1;
1967
+ }
1968
+
1969
+ static uint64_t rt_open_url(const char *url) {
1970
+ char cmd[4096];
1971
+ #ifdef _WIN32
1972
+ char q[2048];
1973
+ rt_win_dq(url, q, sizeof(q));
1974
+ snprintf(cmd, sizeof(cmd), "cmd /c start \"\" \"%s\"", q);
1975
+ #else
1976
+ char q[2048];
1977
+ rt_shell_sq(url, q, sizeof(q));
1978
+ #ifdef __APPLE__
1979
+ snprintf(cmd, sizeof(cmd), "open '%s'", q);
1980
+ #else
1981
+ snprintf(cmd, sizeof(cmd), "xdg-open '%s' 2>/dev/null", q);
1982
+ #endif
1983
+ #endif
1984
+ return system(cmd) == 0 ? 0 : (uint64_t)-1;
1985
+ }
1986
+
1987
+ /* ---------------- 键盘监听 / 行输入 (SYS 116-118, 131) ---------------- */
1988
+
1989
+ #define RT_KEYQ 256
1990
+
1991
+ static unsigned int rt_keyq[RT_KEYQ];
1992
+ static int rt_keyq_head = 0;
1993
+ static int rt_keyq_tail = 0;
1994
+ static int rt_key_ready = 0;
1995
+
1996
+ static void rt_key_push(unsigned int code) {
1997
+ int next = (rt_keyq_tail + 1) % RT_KEYQ;
1998
+ if (next == rt_keyq_head) return;
1999
+ rt_keyq[rt_keyq_tail] = code;
2000
+ rt_keyq_tail = next;
2001
+ }
2002
+
2003
+ static int rt_key_empty(void) { return rt_keyq_head == rt_keyq_tail; }
2004
+
2005
+ static unsigned int rt_key_pop(void) {
2006
+ unsigned int code;
2007
+ if (rt_key_empty()) return 0;
2008
+ code = rt_keyq[rt_keyq_head];
2009
+ rt_keyq_head = (rt_keyq_head + 1) % RT_KEYQ;
2010
+ return code;
2011
+ }
2012
+
2013
+ #ifdef _WIN32
2014
+ static unsigned int rt_key_surrogate = 0;
2015
+ static DWORD rt_key_saved_mode = 0;
2016
+ static int rt_key_mode_valid = 0;
2017
+
2018
+ static void rt_key_reset_state(void) { rt_key_surrogate = 0; }
2019
+ static void rt_key_restore_mode(void) {
2020
+ if (rt_key_mode_valid) {
2021
+ SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), rt_key_saved_mode);
2022
+ rt_key_mode_valid = 0;
2023
+ }
2024
+ }
2025
+ static void rt_key_apply_raw(void) {
2026
+ DWORD raw = rt_key_saved_mode
2027
+ & ~(ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT
2028
+ | ENABLE_ECHO_INPUT | ENABLE_MOUSE_INPUT);
2029
+ raw |= ENABLE_EXTENDED_FLAGS;
2030
+ raw &= ~ENABLE_QUICK_EDIT_MODE;
2031
+ SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), raw);
2032
+ }
2033
+ static void rt_key_enable(void) {
2034
+ DWORD mode;
2035
+ HANDLE h = GetStdHandle(STD_INPUT_HANDLE);
2036
+ if (rt_key_ready) return;
2037
+ if (!GetConsoleMode(h, &mode)) return;
2038
+ rt_key_saved_mode = mode;
2039
+ rt_key_mode_valid = 1;
2040
+ atexit(rt_key_restore_mode);
2041
+ rt_key_apply_raw();
2042
+ rt_key_ready = 1;
2043
+ }
2044
+ static void rt_key_suspend(void) {
2045
+ if (rt_key_mode_valid)
2046
+ SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), rt_key_saved_mode);
2047
+ }
2048
+ static void rt_key_resume(void) {
2049
+ if (rt_key_ready) rt_key_apply_raw();
2050
+ }
2051
+ static void rt_key_drain(void) {
2052
+ INPUT_RECORD rec;
2053
+ DWORD n = 0, avail = 0;
2054
+ HANDLE h;
2055
+ if (!rt_key_ready) return;
2056
+ h = GetStdHandle(STD_INPUT_HANDLE);
2057
+ if (!GetNumberOfConsoleInputEvents(h, &avail)) return;
2058
+ while (avail > 0) {
2059
+ DWORD vk, st;
2060
+ wchar_t ch;
2061
+ unsigned int code = 0;
2062
+ int ctrl, shift;
2063
+ avail--;
2064
+ if (!ReadConsoleInputW(h, &rec, 1, &n) || n == 0) break;
2065
+ if (rec.EventType != KEY_EVENT) continue;
2066
+ if (!rec.Event.KeyEvent.bKeyDown) continue;
2067
+ vk = rec.Event.KeyEvent.wVirtualKeyCode;
2068
+ st = rec.Event.KeyEvent.dwControlKeyState;
2069
+ ch = rec.Event.KeyEvent.uChar.UnicodeChar;
2070
+ ctrl = (st & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) != 0;
2071
+ shift = (st & SHIFT_PRESSED) != 0;
2072
+ switch (vk) {
2073
+ case VK_UP: code = ctrl ? 1101 : (shift ? 1105 : 1001); break;
2074
+ case VK_DOWN: code = ctrl ? 1102 : (shift ? 1106 : 1002); break;
2075
+ case VK_LEFT: code = ctrl ? 1103 : (shift ? 1107 : 1003); break;
2076
+ case VK_RIGHT: code = ctrl ? 1104 : (shift ? 1108 : 1004); break;
2077
+ case VK_HOME: code = 1005; break;
2078
+ case VK_END: code = 1006; break;
2079
+ case VK_PRIOR: code = 1007; break;
2080
+ case VK_NEXT: code = 1008; break;
2081
+ case VK_INSERT: code = 1009; break;
2082
+ case VK_DELETE: code = 1010; break;
2083
+ case VK_TAB:
2084
+ if (shift) code = 1109;
2085
+ break;
2086
+ default:
2087
+ if (vk >= VK_F1 && vk <= VK_F12)
2088
+ code = 1021 + (unsigned int)(vk - VK_F1);
2089
+ break;
2090
+ }
2091
+ if (!code && ch) {
2092
+ if (ch >= 0xD800 && ch <= 0xDBFF) {
2093
+ rt_key_surrogate = (unsigned int)ch;
2094
+ continue;
2095
+ }
2096
+ if (ch >= 0xDC00 && ch <= 0xDFFF && rt_key_surrogate) {
2097
+ code = 0x10000
2098
+ + ((rt_key_surrogate - 0xD800) << 10)
2099
+ + ((unsigned int)ch - 0xDC00);
2100
+ rt_key_surrogate = 0;
2101
+ } else {
2102
+ code = (unsigned int)ch;
2103
+ }
2104
+ }
2105
+ if (code) rt_key_push(code);
2106
+ }
2107
+ }
2108
+ static void rt_key_flush_platform(void) {
2109
+ FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
2110
+ }
2111
+ #else
2112
+ static struct termios rt_key_tio;
2113
+ static int rt_key_tio_valid = 0;
2114
+ static void rt_key_reset_state(void) { }
2115
+ static void rt_key_apply_raw(void) {
2116
+ struct termios t = rt_key_tio;
2117
+ t.c_lflag &= ~(ICANON | ECHO | ISIG);
2118
+ t.c_cc[VMIN] = 0;
2119
+ t.c_cc[VTIME] = 0;
2120
+ tcsetattr(STDIN_FILENO, TCSANOW, &t);
2121
+ }
2122
+ static void rt_key_restore_at_exit(void) {
2123
+ if (rt_key_tio_valid)
2124
+ tcsetattr(STDIN_FILENO, TCSANOW, &rt_key_tio);
2125
+ }
2126
+ static void rt_key_enable(void) {
2127
+ if (rt_key_ready) return;
2128
+ if (!isatty(STDIN_FILENO)) return;
2129
+ if (tcgetattr(STDIN_FILENO, &rt_key_tio) != 0) return;
2130
+ rt_key_tio_valid = 1;
2131
+ atexit(rt_key_restore_at_exit);
2132
+ rt_key_apply_raw();
2133
+ rt_key_ready = 1;
2134
+ }
2135
+ /* 行输入前临时恢复熟模式, 结束后恢复 raw (与 VM 的 lineInputBegin/End 一致) */
2136
+ static void rt_key_suspend(void) {
2137
+ if (!rt_key_ready || !rt_key_tio_valid) return;
2138
+ tcsetattr(STDIN_FILENO, TCSANOW, &rt_key_tio);
2139
+ }
2140
+ static void rt_key_resume(void) {
2141
+ if (!rt_key_ready || !rt_key_tio_valid) return;
2142
+ rt_key_apply_raw();
2143
+ }
2144
+ static int rt_key_esc = 0;
2145
+ static char rt_key_escnum[16];
2146
+ static int rt_key_escn = 0;
2147
+ static int rt_key_u8n = 0;
2148
+ static unsigned int rt_key_u8acc = 0;
2149
+
2150
+ static int rt_key_mod(void) {
2151
+ int start = -1, i, n = 0;
2152
+ for (i = 0; i < rt_key_escn; i++) {
2153
+ if (rt_key_escnum[i] == ';') start = i + 1;
2154
+ else if (rt_key_escnum[i] < '0' || rt_key_escnum[i] > '9') return 1;
2155
+ }
2156
+ if (start < 0 || start >= rt_key_escn) return 1;
2157
+ for (i = start; i < rt_key_escn; i++)
2158
+ n = n * 10 + (rt_key_escnum[i] - '0');
2159
+ return n < 2 ? 1 : n;
2160
+ }
2161
+
2162
+ static unsigned int rt_key_tilde(void) {
2163
+ int i, n = 0;
2164
+ for (i = 0; i < rt_key_escn; i++) {
2165
+ if (rt_key_escnum[i] == ';') break;
2166
+ if (rt_key_escnum[i] < '0' || rt_key_escnum[i] > '9') return 0;
2167
+ n = n * 10 + (rt_key_escnum[i] - '0');
2168
+ }
2169
+ switch (n) {
2170
+ case 1: return 1005; case 2: return 1009; case 3: return 1010;
2171
+ case 4: return 1006; case 5: return 1007; case 6: return 1008;
2172
+ case 11: return 1021; case 12: return 1022; case 13: return 1023;
2173
+ case 14: return 1024; case 15: return 1025; case 17: return 1026;
2174
+ case 18: return 1027; case 19: return 1028; case 20: return 1029;
2175
+ case 21: return 1030; case 23: return 1031; case 24: return 1032;
2176
+ }
2177
+ return 0;
2178
+ }
2179
+
2180
+ static unsigned int rt_key_feed_plain(unsigned char b) {
2181
+ if (rt_key_u8n > 0) {
2182
+ if ((b & 0xC0) != 0x80) {
2183
+ rt_key_u8n = 0;
2184
+ rt_key_u8acc = 0;
2185
+ return rt_key_feed_plain(b);
2186
+ }
2187
+ rt_key_u8acc = (rt_key_u8acc << 6) | (unsigned int)(b & 0x3F);
2188
+ rt_key_u8n--;
2189
+ if (rt_key_u8n > 0) return 0;
2190
+ {
2191
+ unsigned int cp = rt_key_u8acc;
2192
+ rt_key_u8acc = 0;
2193
+ if (cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF))
2194
+ return 0xFFFD;
2195
+ return cp;
2196
+ }
2197
+ }
2198
+ if (b == 0x1B) { rt_key_esc = 1; return 0; }
2199
+ if (b >= 0xC2 && b <= 0xDF) {
2200
+ rt_key_u8n = 1; rt_key_u8acc = b & 0x1F; return 0;
2201
+ }
2202
+ if (b >= 0xE0 && b <= 0xEF) {
2203
+ rt_key_u8n = 2; rt_key_u8acc = b & 0x0F; return 0;
2204
+ }
2205
+ if (b >= 0xF0 && b <= 0xF4) {
2206
+ rt_key_u8n = 3; rt_key_u8acc = b & 0x07; return 0;
2207
+ }
2208
+ return (unsigned int)b;
2209
+ }
2210
+
2211
+ static unsigned int rt_key_feed(unsigned char b) {
2212
+ unsigned int base = 0;
2213
+ if (rt_key_esc == 1) {
2214
+ if (b == '[') { rt_key_esc = 2; rt_key_escn = 0; return 0; }
2215
+ if (b == 'O') { rt_key_esc = 3; return 0; }
2216
+ if (b == 0x1B) { rt_key_esc = 1; return 0x1B; }
2217
+ rt_key_esc = 0;
2218
+ rt_key_push((unsigned int)b);
2219
+ return 0x1B;
2220
+ }
2221
+ if (rt_key_esc == 2) {
2222
+ if ((b >= '0' && b <= '9') || b == ';') {
2223
+ if (rt_key_escn < 15) rt_key_escnum[rt_key_escn++] = (char)b;
2224
+ return 0;
2225
+ }
2226
+ rt_key_esc = 0;
2227
+ if (b == '~') return rt_key_tilde();
2228
+ if (b == 'Z') return 1109;
2229
+ switch (b) {
2230
+ case 'A': base = 1001; break;
2231
+ case 'B': base = 1002; break;
2232
+ case 'C': base = 1003; break;
2233
+ case 'D': base = 1004; break;
2234
+ case 'H': base = 1005; break;
2235
+ case 'F': base = 1006; break;
2236
+ }
2237
+ if (base) {
2238
+ int mod = rt_key_mod();
2239
+ if (mod > 1) {
2240
+ int m = mod - 1;
2241
+ if (m & 4) return base - 1001 + 1101;
2242
+ if (m & 1) return base - 1001 + 1105;
2243
+ }
2244
+ return base;
2245
+ }
2246
+ return 0;
2247
+ }
2248
+ if (rt_key_esc == 3) {
2249
+ rt_key_esc = 0;
2250
+ switch (b) {
2251
+ case 'A': return 1001;
2252
+ case 'B': return 1002;
2253
+ case 'C': return 1003;
2254
+ case 'D': return 1004;
2255
+ case 'H': return 1005;
2256
+ case 'F': return 1006;
2257
+ case 'P': return 1021;
2258
+ case 'Q': return 1022;
2259
+ case 'R': return 1023;
2260
+ case 'S': return 1024;
2261
+ }
2262
+ return 0;
2263
+ }
2264
+ return rt_key_feed_plain(b);
2265
+ }
2266
+
2267
+ static void rt_key_drain(void) {
2268
+ unsigned char b;
2269
+ if (!rt_key_ready) return;
2270
+ while (read(STDIN_FILENO, &b, 1) == 1) {
2271
+ unsigned int code = rt_key_feed(b);
2272
+ if (code) rt_key_push(code);
2273
+ }
2274
+ }
2275
+ static void rt_key_flush_platform(void) {
2276
+ tcflush(STDIN_FILENO, TCIFLUSH);
2277
+ }
2278
+ #endif
2279
+
2280
+ static uint64_t rt_key_hit(void) {
2281
+ rt_key_enable();
2282
+ if (rt_key_empty()) rt_key_drain();
2283
+ return rt_key_empty() ? 0 : 1;
2284
+ }
2285
+
2286
+ static uint64_t rt_key_get(void) {
2287
+ rt_key_enable();
2288
+ if (rt_key_empty()) rt_key_drain();
2289
+ return rt_key_empty() ? (uint64_t)-1 : (uint64_t)rt_key_pop();
2290
+ }
2291
+
2292
+ static uint64_t rt_key_flush(void) {
2293
+ rt_keyq_head = rt_keyq_tail = 0;
2294
+ rt_key_reset_state();
2295
+ #ifndef _WIN32
2296
+ rt_key_esc = 0;
2297
+ rt_key_escn = 0;
2298
+ rt_key_u8n = 0;
2299
+ rt_key_u8acc = 0;
2300
+ #endif
2301
+ if (rt_key_ready) rt_key_flush_platform();
2302
+ return 0;
2303
+ }
2304
+
2305
+ static uint64_t rt_readline(void) {
2306
+ char buf[4096];
2307
+ size_t n;
2308
+ rt_key_suspend();
2309
+ if (!fgets(buf, sizeof(buf), stdin)) {
2310
+ rt_key_resume();
2311
+ return rt_empty();
2312
+ }
2313
+ n = strlen(buf);
2314
+ while (n > 0 && (buf[n - 1] == '\n' || buf[n - 1] == '\r')) buf[--n] = 0;
2315
+ rt_key_resume();
2316
+ return rt_dupstr(buf);
2317
+ }
2318
+
2319
+ static double rt_bits2f(uint64_t bits) { double d;
2320
+ memcpy(&d, &bits, 8);
2321
+ return d;
2322
+ }
2323
+
2324
+ static uint64_t rt_f2bits(double d) {
2325
+ uint64_t bits;
2326
+ memcpy(&bits, &d, 8);
2327
+ return bits;
2328
+ }
2329
+
2330
+ static int rt_finish(void) {
2331
+ fflush(OUTP);
2332
+ if (ERRMSG) {
2333
+ fprintf(stderr, "runtime error: %s\n", ERRMSG);
2334
+ return 1;
2335
+ }
2336
+ return 0;
2337
+ }
2338
+ '''
2339
+
2340
+
2341
+ def _u64(v: Any) -> int:
2342
+ return int(v) & 0xFFFFFFFFFFFFFFFF
2343
+
2344
+
2345
+ def _i64(v: Any) -> int:
2346
+ v = int(v) & 0xFFFFFFFFFFFFFFFF
2347
+ return v - (1 << 64) if v >> 63 else v
2348
+
2349
+
2350
+ def _c_str(text: str) -> str:
2351
+ out = []
2352
+ for byte in text.encode('utf-8'):
2353
+ if byte in (0x22, 0x5C):
2354
+ out.append('\\' + chr(byte))
2355
+ elif 32 <= byte < 127:
2356
+ out.append(chr(byte))
2357
+ else:
2358
+ out.append('\\%03o' % byte)
2359
+ return '"' + ''.join(out) + '"'
2360
+
2361
+
2362
+ class _Emitter:
2363
+ def __init__(self,
2364
+ instructions: Sequence[Instruction],
2365
+ labels: Dict[str, int],
2366
+ segments: Segments,
2367
+ entry_pc: int,
2368
+ mem_size: int,
2369
+ sp: int,
2370
+ heap_base: int):
2371
+ self.instructions = list(instructions)
2372
+ self.labels = dict(labels)
2373
+ self.segments = list(segments)
2374
+ self.entry_pc = int(entry_pc)
2375
+ self.mem_size = int(mem_size)
2376
+ self.sp = int(sp)
2377
+ self.heap_base = int(heap_base)
2378
+ self.lines: List[str] = []
2379
+ self._need_dispatch = False
2380
+
2381
+ # ---------- 基础设施 ----------
2382
+
2383
+ def emit(self, text: str = '') -> None:
2384
+ self.lines.append(text)
2385
+
2386
+ def code(self, text: str) -> None:
2387
+ self.lines.append('\t' + text)
2388
+
2389
+ def fail(self, expr: str) -> None:
2390
+ self.code(f'if (!({expr})) {{ goto Lerror; }}')
2391
+
2392
+ def target(self, arg: Tuple[Any, ...]) -> Optional[int]:
2393
+ kind = arg[0]
2394
+ if kind == 'label':
2395
+ pc = self.labels.get(arg[1])
2396
+ elif kind == 'imm':
2397
+ pc = int(arg[1])
2398
+ else:
2399
+ return None
2400
+ if pc is None or pc < 0 or pc >= len(self.instructions):
2401
+ return None
2402
+ return int(pc)
2403
+
2404
+ def value(self, arg: Tuple[Any, ...]) -> Optional[str]:
2405
+ kind = arg[0]
2406
+ if kind == 'reg':
2407
+ return f'R[{int(arg[1])}]'
2408
+ if kind == 'imm':
2409
+ return f'UINT64_C(0x{_u64(arg[1]):x})'
2410
+ if kind == 'str':
2411
+ return f'UINT64_C(0x{_u64(arg[1]):x})'
2412
+ if kind == 'float':
2413
+ return f'UINT64_C(0x{struct.unpack("<Q", struct.pack("<d", float(arg[1])))[0]:x})'
2414
+ return None
2415
+
2416
+ def address(self, arg: Tuple[Any, ...]) -> Optional[str]:
2417
+ kind = arg[0]
2418
+ if kind == 'reg':
2419
+ return f'R[{int(arg[1])}]'
2420
+ if kind == 'imm':
2421
+ return f'UINT64_C(0x{_u64(arg[1]):x})'
2422
+ if kind == 'mem':
2423
+ # [reg + off] 形式的基址寄存器寻址
2424
+ base = int(arg[1])
2425
+ off = _i64(arg[2])
2426
+ if off == 0:
2427
+ return f'R[{base}]'
2428
+ return f'(R[{base}] + UINT64_C(0x{_u64(off):x}))'
2429
+ return None
2430
+
2431
+ def dispatch(self) -> None:
2432
+ self._need_dispatch = True
2433
+
2434
+ # ---------- 单条指令 ----------
2435
+
2436
+ def instruction(self, op: str,
2437
+ args: List[Tuple[Any, ...]], idx: int) -> None:
2438
+ # ---- 数据搬运 ----
2439
+ if op == 'MOV':
2440
+ v = self.value(args[1])
2441
+ if v is None:
2442
+ self.unsupported(op)
2443
+ else:
2444
+ self.code(f'R[{int(args[0][1])}] = {v};')
2445
+ return
2446
+
2447
+ # ---- 二元整数运算 (rd op= rhs) ----
2448
+ binary = {
2449
+ 'ADD': 'R[{rd}] = rt_add(R[{rd}], {v});',
2450
+ 'SUB': 'R[{rd}] = rt_sub(R[{rd}], {v});',
2451
+ 'MUL': 'R[{rd}] = rt_mul(R[{rd}], {v});',
2452
+ 'AND': 'R[{rd}] = R[{rd}] & {v};',
2453
+ 'OR': 'R[{rd}] = R[{rd}] | {v};',
2454
+ 'XOR': 'R[{rd}] = R[{rd}] ^ {v};',
2455
+ 'SHL': 'R[{rd}] = rt_shl(R[{rd}], {v});',
2456
+ 'SHR': 'R[{rd}] = rt_shr(R[{rd}], {v});',
2457
+ 'ASR': 'R[{rd}] = rt_asr(R[{rd}], {v});',
2458
+ 'ROR': 'R[{rd}] = rt_ror(R[{rd}], {v});',
2459
+ }
2460
+ if op in binary:
2461
+ rd = int(args[0][1])
2462
+ v = self.value(args[1])
2463
+ if v is None:
2464
+ self.unsupported(op)
2465
+ else:
2466
+ self.code(binary[op].format(rd=rd, v=v))
2467
+ return
2468
+ if op == 'DIV':
2469
+ rd = int(args[0][1])
2470
+ v = self.value(args[1])
2471
+ if v is None:
2472
+ self.unsupported(op)
2473
+ else:
2474
+ self.code(f'R[{rd}] = rt_sdiv(R[{rd}], {v});')
2475
+ self.code('if (ERRMSG) goto Lerror;')
2476
+ return
2477
+
2478
+ # ---- 三操作数形式: op rd, rs, v ----
2479
+ if op in ('ADDI', 'LSL', 'LSR', 'ASR', 'XORI', 'ORI', 'ANDI'):
2480
+ rd, rs = int(args[0][1]), int(args[1][1])
2481
+ v = self.value(args[2]) if len(args) > 2 else None
2482
+ if v is None:
2483
+ self.unsupported(op)
2484
+ return
2485
+ expr = {
2486
+ 'ADDI': f'rt_add(R[{rs}], {v})',
2487
+ 'LSL': f'rt_shl(R[{rs}], {v})',
2488
+ 'LSR': f'rt_shr(R[{rs}], {v})',
2489
+ 'ASR': f'rt_asr(R[{rs}], {v})',
2490
+ 'XORI': f'(R[{rs}] ^ {v})',
2491
+ 'ORI': f'(R[{rs}] | {v})',
2492
+ 'ANDI': f'(R[{rs}] & {v})',
2493
+ }[op]
2494
+ self.code(f'R[{rd}] = {expr};')
2495
+ return
2496
+
2497
+ if op in ('INC', 'DEC'):
2498
+ rd = int(args[0][1])
2499
+ delta = '+ 1' if op == 'INC' else '- 1'
2500
+ self.code(f'R[{rd}] = R[{rd}] {delta};')
2501
+ return
2502
+ if op == 'MVN':
2503
+ rd = int(args[0][1])
2504
+ v = self.value(args[1])
2505
+ if v is None:
2506
+ self.unsupported(op)
2507
+ else:
2508
+ self.code(f'R[{rd}] = ~{v};')
2509
+ return
2510
+ if op == 'CMP':
2511
+ a, b = self.value(args[0]), self.value(args[1])
2512
+ if a is None or b is None:
2513
+ self.unsupported(op)
2514
+ else:
2515
+ self.code(f'rt_cmp({a}, {b});')
2516
+ return
2517
+
2518
+ # ---- 栈 ----
2519
+ if op == 'PUSH':
2520
+ v = self.value(args[0])
2521
+ if v is None:
2522
+ self.unsupported(op)
2523
+ else:
2524
+ self.fail(f'rt_push({v})')
2525
+ return
2526
+ if op == 'POP':
2527
+ self.fail(f'rt_pop({int(args[0][1])})')
2528
+ return
2529
+
2530
+ # ---- 内存 ----
2531
+ widths = {'LOAD': (4, 0), 'LW': (4, 1), 'LD': (8, 1), 'LB': (1, 1),
2532
+ 'LH': (2, 1), 'LDR': (4, 0)}
2533
+ if op in widths:
2534
+ width, sign = widths[op]
2535
+ addr = self.address(args[1])
2536
+ if addr is None:
2537
+ self.unsupported(op)
2538
+ else:
2539
+ self.fail(f'rt_load({int(args[0][1])}, {addr}, {width}, {sign})')
2540
+ return
2541
+ stores = {'STORE': 4, 'SW': 4, 'STR': 4, 'SD': 8, 'SB': 1, 'SH': 2}
2542
+ if op in stores:
2543
+ addr = self.address(args[1])
2544
+ if addr is None:
2545
+ self.unsupported(op)
2546
+ else:
2547
+ self.fail(f'rt_store(R[{int(args[0][1])}], {addr}, '
2548
+ f'{stores[op]})')
2549
+ return
2550
+
2551
+ if op == 'B':
2552
+ cond_arg = next((a for a in args if a[0] == 'cond'), None)
2553
+ target_arg = next((a for a in args if a[0] != 'cond'), None)
2554
+ target = self.target(target_arg) if target_arg else None
2555
+ if cond_arg is None or target is None:
2556
+ self.unsupported(op)
2557
+ return
2558
+ code = _COND_CODES.get(str(cond_arg[1]).upper())
2559
+ if code is None:
2560
+ self.unsupported(op)
2561
+ return
2562
+ self.code(f'if (rt_cond({code})) goto L{target};')
2563
+ return
2564
+ if op in ('CBZ', 'CBNZ'):
2565
+ target = self.target(args[-1])
2566
+ if target is None:
2567
+ self.unsupported(op)
2568
+ return
2569
+ test = '==' if op == 'CBZ' else '!='
2570
+ self.code(f'if (R[{int(args[0][1])}] {test} 0) goto L{target};')
2571
+ return
2572
+
2573
+ # ---- 控制流 ----
2574
+ if op == 'JMP':
2575
+ target = self.target(args[0])
2576
+ if target is None:
2577
+ self.unsupported(op)
2578
+ else:
2579
+ self.code(f'goto L{target};')
2580
+ return
2581
+ if op in ('JZ', 'JE', 'JNZ', 'JL', 'JG'):
2582
+ target = self.target(args[0])
2583
+ if target is None:
2584
+ self.unsupported(op)
2585
+ return
2586
+ cond = {'JZ': 'ZF', 'JE': 'ZF', 'JNZ': '!ZF',
2587
+ 'JL': '(NF != VF)', 'JG': '(!ZF && NF == VF)'}[op]
2588
+ self.code(f'if ({cond}) goto L{target};')
2589
+ return
2590
+ if op in ('CALL', 'BL'):
2591
+ target = self.target(args[0])
2592
+ if target is None:
2593
+ self.unsupported(op)
2594
+ return
2595
+ self.fail(f'rt_push(UINT64_C({idx + 1}))')
2596
+ self.code(f'goto L{target};')
2597
+ return
2598
+ if op == 'RET':
2599
+ self.fail('rt_pop_ret()')
2600
+ self.code('pc = RETADDR; goto Ldispatch;')
2601
+ return
2602
+ if op == 'HALT':
2603
+ self.code('goto Ldone;')
2604
+ return
2605
+
2606
+ # ---- I/O ----
2607
+ if op == 'OUT':
2608
+ kind, value, extra = self.out_operand(args[0])
2609
+ self.code(value)
2610
+ return
2611
+ if op == 'SYS':
2612
+ if args[0][0] != 'imm':
2613
+ self.unsupported(op)
2614
+ return
2615
+ code = _u64(args[0][1])
2616
+ if code == 137: # ALLOCFRAME
2617
+ self.fail('rt_allocframe(R[0])')
2618
+ return
2619
+ simple = {
2620
+ 0: 'R[0] = rt_f2bits(sqrt(rt_bits2f(R[0])));', # SQRT
2621
+ 1: 'R[0] = rt_f2bits(pow(rt_bits2f(R[0]), rt_bits2f(R[1])));',
2622
+ 2: 'R[0] = (uint64_t)llabs((long long)R[0]);', # ABS
2623
+ 3: 'R[0] = rt_f2bits(sin(rt_bits2f(R[0])));', # SIN
2624
+ 4: 'R[0] = rt_f2bits(cos(rt_bits2f(R[0])));', # COS
2625
+ 5: 'R[0] = rt_f2bits(tan(rt_bits2f(R[0])));', # TAN
2626
+ 6: 'R[0] = rt_f2bits(rt_bits2f(R[0]) + rt_bits2f(R[1]));',
2627
+ 7: 'R[0] = rt_f2bits(rt_bits2f(R[0]) - rt_bits2f(R[1]));',
2628
+ 8: 'R[0] = rt_f2bits(rt_bits2f(R[0]) * rt_bits2f(R[1]));',
2629
+ 9: ('if (rt_bits2f(R[1]) == 0.0) { rt_fail("Float division '
2630
+ 'by zero (SYS)"); goto Lerror; } '
2631
+ 'R[0] = rt_f2bits(rt_bits2f(R[0]) / rt_bits2f(R[1]));'),
2632
+ 10: ('{ double fa = rt_bits2f(R[0]), fb = rt_bits2f(R[1]); '
2633
+ 'R[0] = fa < fb ? (uint64_t)-1 : (fa > fb ? 1 : 0); }'),
2634
+ 11: 'R[0] = (uint64_t)(int64_t)rt_bits2f(R[0]);', # FTOI
2635
+ 12: 'R[0] = rt_f2bits((double)(int64_t)R[0]);', # ITOF
2636
+ 13: 'R[0] = rt_rand();', # RAND
2637
+ 14: 'rt_rand_state = R[0] ? R[0] : 1;', # SRAND
2638
+ 15: 'R[0] = (uint64_t)time(NULL);', # TIME
2639
+ 16: 'R[0] = rt_strlen(R[0]);', # STRLEN
2640
+ 17: 'R[0] = rt_strcmp(R[0], R[1]);', # STRCMP
2641
+ 18: 'R[0] = rt_strcpy(R[0], R[1], 0);', # STRCPY
2642
+ 19: 'R[0] = rt_strcpy(R[0], R[1], 1);', # STRCAT
2643
+ 20: 'R[0] = rt_heap(R[0]);', # MALLOC
2644
+ 21: 'rt_out_float(R[0]);', # PRINT_FLOAT
2645
+ 22: 'R[0] = rt_itoa((int64_t)R[0]);', # ITOA
2646
+ 23: 'R[0] = rt_ftoa(R[0]);', # FTOA
2647
+ 24: 'rt_out_str(R[0]);', # PRINT_STR
2648
+ 25: 'R[0] = rt_strconcat(R[0], R[1]);', # STR_CONCAT
2649
+ 26: 'R[0] = rt_boolstr(R[0]);', # BOOL_STR
2650
+ 27: 'rt_abort(R[0]);', # ABORT
2651
+ 28: 'R[0] = rt_substr(R[0], R[1], R[2]);', # SUBSTR
2652
+ 29: 'R[0] = rt_indexof(R[0], R[1]);', # INDEXOF
2653
+ 30: ('R[0] = rt_dupstr(rt_cstr(R[0])); '
2654
+ 'if (R[0]) rt_to_upper((char *)(MEM + R[0]));'), # TOUPPER
2655
+ 31: ('R[0] = rt_dupstr(rt_cstr(R[0])); '
2656
+ 'if (R[0]) rt_to_lower((char *)(MEM + R[0]));'), # TOLOWER
2657
+ 32: 'R[0] = rt_f2bits(floor(rt_bits2f(R[0])));', # FLOOR
2658
+ 33: 'R[0] = rt_f2bits(ceil(rt_bits2f(R[0])));', # CEIL
2659
+ 34: 'R[0] = rt_f2bits(floor(rt_bits2f(R[0]) + 0.5));', # ROUND
2660
+ 35: ('{ const char *s = rt_cstr(R[0]); char *end = NULL; '
2661
+ 'long long v = strtoll(s, &end, 10); '
2662
+ 'R[0] = (end && end != s) ? (uint64_t)v : 0; }'),
2663
+ 36: 'R[0] = rt_trim(R[0], 1, 1);', # TRIM
2664
+ 37: 'R[0] = rt_trim(R[0], 1, 0);', # LTRIM
2665
+ 38: 'R[0] = rt_trim(R[0], 0, 1);', # RTRIM
2666
+ 43: 'R[0] = rt_canvas_new(R[0], R[1]);', # CANVAS_NEW
2667
+ 44: 'R[0] = rt_canvas_set(R[0]);', # CANVAS_SET
2668
+ 45: 'R[0] = rt_canvas_rect(R[0], R[1], R[2], R[3]);', # RECT
2669
+ 46: 'R[0] = rt_canvas_circle(R[0], R[1], R[2]);', # CIRCLE
2670
+ 47: 'R[0] = rt_canvas_text(R[0], R[1], R[2]);', # CANVASTEXT
2671
+ 48: 'R[0] = rt_canvas_line(R[0], R[1], R[2], R[3]);', # LINE
2672
+ 49: 'R[0] = rt_canvas_save(rt_cstr(R[0]));', # SAVE
2673
+ 50: 'R[0] = (uint64_t)-1; /* 无窗口环境: show_canvas 不支持 */',
2674
+ 51: 'R[0] = rt_readfile(rt_cstr(R[0]));', # FILE_READ
2675
+ 52: 'R[0] = (uint64_t)(int64_t)rt_writefile('
2676
+ 'rt_cstr(R[0]), rt_cstr(R[1]), 0);', # WRITE
2677
+ 53: 'R[0] = (uint64_t)(int64_t)rt_writefile('
2678
+ 'rt_cstr(R[0]), rt_cstr(R[1]), 1);', # APPEND
2679
+ 54: 'R[0] = rt_fileexists(rt_cstr(R[0]));', # EXISTS
2680
+ 55: 'R[0] = rt_filedelete(rt_cstr(R[0]));', # DELETE
2681
+ 56: 'R[0] = rt_filesize(rt_cstr(R[0]));', # SIZE
2682
+ 57: 'R[0] = rt_mkdirs(rt_cstr(R[0]));', # MKDIR
2683
+ 58: 'R[0] = rt_dirlist(rt_cstr(R[0]));', # DIRLIST
2684
+ 59: 'R[0] = rt_exec_cmd(rt_cstr(R[0]));', # EXEC
2685
+ 60: 'R[0] = rt_exec_output(rt_cstr(R[0]));', # EXECOUTPUT
2686
+ 61: 'R[0] = rt_getenv(rt_cstr(R[0]));', # GETENV
2687
+ 62: 'R[0] = rt_setenv(rt_cstr(R[0]), rt_cstr(R[1]));', # SETENV
2688
+ 63: 'R[0] = rt_osname();', # OSNAME
2689
+ 64: 'R[0] = rt_hostname();', # HOSTNAME
2690
+ 65: 'R[0] = rt_username();', # USERNAME
2691
+ 66: 'R[0] = rt_cwd();', # CWD
2692
+ 67: 'R[0] = rt_homedir();', # HOMEDIR
2693
+ 86: 'R[0] = rt_dir_remove(rt_cstr(R[0]));', # DIR_REMOVE
2694
+ 80: 'R[0] = rt_path_join(rt_cstr(R[0]), rt_cstr(R[1]));', # JOIN
2695
+ 81: 'R[0] = rt_path_basename(rt_cstr(R[0]));', # BASENAME
2696
+ 82: 'R[0] = rt_path_dirname(rt_cstr(R[0]));', # DIRNAME
2697
+ 83: 'R[0] = rt_path_abs(rt_cstr(R[0]));', # ABS
2698
+ 84: 'R[0] = rt_file_copy(rt_cstr(R[0]), rt_cstr(R[1]));', # COPY
2699
+ 85: 'R[0] = rt_file_move(rt_cstr(R[0]), rt_cstr(R[1]));', # MOVE
2700
+ 88: 'R[0] = rt_file_mtime(rt_cstr(R[0]));', # MTIME
2701
+ 87: 'R[0] = rt_is_dir(rt_cstr(R[0]));', # IS_DIR
2702
+ 89: 'R[0] = rt_temp_dir();', # TEMP_DIR
2703
+ 90: 'R[0] = rt_chdir(rt_cstr(R[0]));', # CHDIR
2704
+ 91: 'R[0] = rt_time_ms();', # TIME_MS
2705
+ 92: 'R[0] = rt_sleep_ms(R[0]);', # SLEEP_MS
2706
+ 93: 'R[0] = rt_cpu_count();', # CPU_COUNT
2707
+ 94: 'R[0] = rt_arch_name();', # ARCH_NAME
2708
+ 95: 'R[0] = rt_meminfo();', # MEMINFO
2709
+ 96: 'R[0] = rt_is_android();', # IS_ANDROID
2710
+ 97: 'R[0] = rt_http("GET", rt_cstr(R[0]), "", "");', # HTTP_GET
2711
+ 98: ('R[0] = rt_http("POST", rt_cstr(R[0]), '
2712
+ '"Content-Type: text/plain; charset=utf-8\\r\\n", '
2713
+ 'rt_cstr(R[1]));'), # HTTP_POST
2714
+ 99: 'R[0] = rt_download(R[0], R[1]);', # DOWNLOAD
2715
+ 100: 'R[0] = rt_sha256_hex(R[0]);', # SHA256
2716
+ 101: 'R[0] = rt_b64enc(R[0]);', # B64_ENC
2717
+ 102: 'R[0] = rt_b64dec(R[0]);', # B64_DEC
2718
+ 103: 'R[0] = rt_clip_get();', # CLIPGET
2719
+ 104: 'R[0] = rt_clip_set(rt_cstr(R[0]));', # CLIPSET
2720
+ 105: 'R[0] = rt_notify(rt_cstr(R[0]), rt_cstr(R[1]));', # NOTIFY
2721
+ 106: 'R[0] = rt_open_url(rt_cstr(R[0]));', # OPENURL
2722
+ 116: 'R[0] = rt_key_hit();', # KEYHIT
2723
+ 117: 'R[0] = rt_key_get();', # KEYGET
2724
+ 118: 'R[0] = rt_key_flush();', # KEYFLUSH
2725
+ 131: 'R[0] = rt_readline();', # READLINE
2726
+ 145: 'R[0] = rt_http(rt_cstr(R[0]), rt_cstr(R[1]), '
2727
+ 'rt_cstr(R[2]), rt_cstr(R[3]));', # HTTP_REQ
2728
+ 146: 'R[0] = (uint64_t)LASTHTTPST;', # HTTP_CODE
2729
+ 147: 'R[0] = rt_tcp_dial(rt_cstr(R[0]), R[1]);', # TCP_DIAL
2730
+ 148: 'R[0] = rt_tcp_send(R[0], R[1], R[2]);', # TCP_SEND
2731
+ 149: 'R[0] = (uint64_t)(int64_t)rt_tcp_recv('
2732
+ 'R[0], R[1], R[2]);', # TCP_RECV
2733
+ 150: 'R[0] = rt_tcp_close(R[0]);', # TCP_CLOSE
2734
+ 151: 'R[0] = rt_tcp_listen(R[0]);', # TCP_LISTEN
2735
+ 152: 'R[0] = rt_tcp_accept(R[0]);', # TCP_ACCEPT
2736
+ 153: 'R[0] = rt_udp_open(R[0]);', # UDP_OPEN
2737
+ 154: 'R[0] = rt_udp_sendto(R[0], rt_cstr(R[1]), R[2], '
2738
+ 'R[3], R[4]);', # UDP_SENDTO
2739
+ 155: 'R[0] = rt_udp_recvfrom(R[0], R[1], R[2], R[3]);', # UDP_RECV
2740
+ 156: 'R[0] = rt_tcp_close(R[0]);', # UDP_CLOSE
2741
+ 157: 'R[0] = rt_dns_lookup(rt_cstr(R[0]));', # DNS_LOOKUP
2742
+ }
2743
+ if code in simple:
2744
+ self.code(simple[code])
2745
+ self.code('if (ERRMSG) goto Lerror;')
2746
+ return
2747
+ self.code(f'rt_unsupported("SYS {code} 未在 C 后端实现");')
2748
+ self.code('goto Lerror;')
2749
+ return
2750
+
2751
+ self.unsupported(op)
2752
+
2753
+ def out_operand(self, arg: Tuple[Any, ...]) -> Tuple[str, str, str]:
2754
+ kind = arg[0]
2755
+ if kind == 'reg':
2756
+ return 'int', f'rt_out_uint(R[{int(arg[1])}]);', ''
2757
+ if kind == 'imm':
2758
+ return 'int', f'rt_out_uint(UINT64_C(0x{_u64(arg[1]):x}));', ''
2759
+ if kind == 'str':
2760
+ return 'str', f'rt_out_str(UINT64_C(0x{_u64(arg[1]):x}));', ''
2761
+ if kind == 'float':
2762
+ bits = struct.unpack('<Q', struct.pack('<d', float(arg[1])))[0]
2763
+ return 'float', f'rt_out_float(UINT64_C(0x{bits:x}));', ''
2764
+ raise CBackendError(f'不支持的 OUT 操作数: {kind}')
2765
+
2766
+ def unsupported(self, op: str) -> None:
2767
+ self.code(f'rt_unsupported("instruction {op} 未在 C 后端实现");')
2768
+ self.code('goto Lerror;')
2769
+
2770
+ # ---------- 整程序 ----------
2771
+
2772
+ def generate(self) -> str:
2773
+ body: List[str] = []
2774
+ self.lines = body
2775
+ for idx, (op, args) in enumerate(self.instructions):
2776
+ self.emit(f'L{idx}:;')
2777
+ try:
2778
+ self.instruction(op, list(args), idx)
2779
+ except CBackendError as e:
2780
+ self.code(f'rt_unsupported({_c_str(str(e))});')
2781
+ self.code('goto Lerror;')
2782
+
2783
+ data: List[str] = []
2784
+ for addr, blob in self.segments:
2785
+ if not blob:
2786
+ continue
2787
+ data.append(f'static const unsigned char seg_{addr:x}[] = {{'
2788
+ + ','.join(str(b) for b in blob) + '};')
2789
+ out: List[str] = [_RUNTIME]
2790
+ out.extend(data)
2791
+ out.append('int main(void) {')
2792
+ out.append('\tif (!rt_init(UINT64_C({}), UINT64_C({}), '
2793
+ 'UINT64_C({}))) {{'.format(
2794
+ self.mem_size, _u64(self.sp), _u64(self.heap_base)))
2795
+ out.append('\t\tfprintf(stderr, "runtime error: cannot allocate '
2796
+ f'{self.mem_size} bytes\\n");')
2797
+ out.append('\t\treturn 1;')
2798
+ out.append('\t}')
2799
+ out.append('\tuint64_t pc = 0;')
2800
+ for addr, blob in self.segments:
2801
+ if blob:
2802
+ out.append(f'\tmemcpy(MEM + UINT64_C(0x{addr:x}), '
2803
+ f'seg_{addr:x}, sizeof(seg_{addr:x}));')
2804
+ out.append('\tgoto L{};'.format(self.entry_pc))
2805
+ out.extend(body)
2806
+ out.append('Ldispatch:;')
2807
+ out.append('\tswitch (pc) {')
2808
+ for idx in range(len(self.instructions)):
2809
+ out.append(f'\tcase {idx}: goto L{idx};')
2810
+ out.append('\tdefault: rt_unsupported("bad jump target"); '
2811
+ 'goto Lerror;')
2812
+ out.append('\t}')
2813
+ out.append('Ldone:;')
2814
+ out.append('\treturn rt_finish();')
2815
+ out.append('Lerror:;')
2816
+ out.append('\treturn rt_finish();')
2817
+ out.append('}')
2818
+ return '\n'.join(out) + '\n'
2819
+
2820
+
2821
+ def emit_c(instructions: Sequence[Instruction], labels: Dict[str, int],
2822
+ segments: Segments, entry_pc: int, mem_size: int, sp: int,
2823
+ heap_base: int) -> str:
2824
+ """生成 C 源码 (纯函数, 便于单测)。"""
2825
+ return _Emitter(instructions, labels, segments, entry_pc, mem_size, sp,
2826
+ heap_base).generate()
2827
+
2828
+
2829
+ _ELF_MACHINE = {'x86_64': 62, 'aarch64': 183, 'arm64': 183}
2830
+ _PE_MACHINE = {'x86_64': 0x8664, 'aarch64': 0xAA64, 'arm64': 0xAA64}
2831
+
2832
+
2833
+ def inspect_binary(path: str, target: str,
2834
+ ) -> Dict[str, object]:
2835
+ """校验产物的文件格式与目标架构 (ELF/PE), 返回可展示的结构摘要。
2836
+
2837
+ Raises:
2838
+ ValueError: 格式、架构或关键头部字段与 ``target`` 不符。
2839
+ """
2840
+ try:
2841
+ spec = toolchain.get_target(target)
2842
+ except toolchain.ToolchainError:
2843
+ goos, goarch = (target.split('/', 1) + ['amd64'])[:2]
2844
+ spec = toolchain.get_target(c_target(goos, goarch))
2845
+ size = os.path.getsize(path)
2846
+ with open(path, 'rb') as f:
2847
+ data = f.read(65536)
2848
+ if not data:
2849
+ raise ValueError(f'产物为空: {path}')
2850
+ arch = spec.triple.split('-', 1)[0].lower()
2851
+
2852
+ if data[:4] == b'\x7fELF':
2853
+ if spec.fmt != 'elf':
2854
+ raise ValueError(f'目标 {target} 应生成 {spec.fmt}, 实际是 ELF')
2855
+ if len(data) < 64:
2856
+ raise ValueError('ELF 头部被截断')
2857
+ cls, endian = data[4], data[5]
2858
+ if cls != 2 or endian != 1:
2859
+ raise ValueError(
2860
+ f'ELF 应为 64 位小端 (class=2, data=1), 实际 {cls}/{endian}')
2861
+ e_type, = struct.unpack_from('<H', data, 16)
2862
+ machine, = struct.unpack_from('<H', data, 18)
2863
+ entry, = struct.unpack_from('<Q', data, 24)
2864
+ phoff, = struct.unpack_from('<Q', data, 32)
2865
+ phnum, = struct.unpack_from('<H', data, 56)
2866
+ if machine != _ELF_MACHINE.get(arch):
2867
+ raise ValueError(
2868
+ f'ELF machine 不匹配: 期望 {_ELF_MACHINE.get(arch)}, 实际 {machine}')
2869
+ if e_type not in (2, 3):
2870
+ raise ValueError(f'ELF 类型异常: {e_type} (期望 EXEC/DYN)')
2871
+ if entry == 0 or phoff == 0 or phnum == 0:
2872
+ raise ValueError('ELF 缺少入口或程序头')
2873
+ return {'format': 'elf', 'target': target, 'size': size,
2874
+ 'bits': 64, 'endian': 'little', 'type': e_type,
2875
+ 'machine': machine, 'entry': entry, 'phnum': phnum}
2876
+
2877
+ if data[:2] == b'MZ':
2878
+ if spec.fmt != 'pe':
2879
+ raise ValueError(f'目标 {target} 应生成 ELF, 实际是 PE')
2880
+ if len(data) < 0x40:
2881
+ raise ValueError('PE 头部被截断')
2882
+ pe_off, = struct.unpack_from('<I', data, 0x3C)
2883
+ if pe_off + 24 + 68 > len(data) or data[pe_off:pe_off + 4] != b'PE\x00\x00':
2884
+ raise ValueError('缺少 PE 签名')
2885
+ machine, = struct.unpack_from('<H', data, pe_off + 4)
2886
+ sections, = struct.unpack_from('<H', data, pe_off + 6)
2887
+ magic, = struct.unpack_from('<H', data, pe_off + 24)
2888
+ subsystem, = struct.unpack_from('<H', data, pe_off + 92)
2889
+ if machine != _PE_MACHINE.get(arch):
2890
+ raise ValueError(
2891
+ f'PE machine 不匹配: 期望 {_PE_MACHINE.get(arch)}, 实际 {machine}')
2892
+ if magic != 0x20B:
2893
+ raise ValueError(f'PE 应为 PE32+ (0x20B), 实际 0x{magic:X}')
2894
+ if subsystem != 3:
2895
+ raise ValueError(f'PE subsystem 应为控制台 (3), 实际 {subsystem}')
2896
+ return {'format': 'pe', 'target': target, 'size': size,
2897
+ 'bits': 64, 'machine': machine, 'sections': sections,
2898
+ 'subsystem': subsystem}
2899
+
2900
+ raise ValueError(f'无法识别的产物格式: {path}')
2901
+
2902
+
2903
+ def compile_instructions(instructions: Sequence[Instruction],
2904
+ labels: Dict[str, int],
2905
+ segments: Segments,
2906
+ entry_pc: int,
2907
+ mem_size: int,
2908
+ sp: int,
2909
+ heap_base: int,
2910
+ out: str,
2911
+ target: Optional[str] = None,
2912
+ optimize: int = 2,
2913
+ keep_c: bool = False,
2914
+ static_link: bool = False,
2915
+ strip_binary: bool = False) -> str:
2916
+ """把指令流编译成独立可执行文件, 返回产物路径。"""
2917
+ target_name = target or _host_target_name()
2918
+ spec = toolchain.get_target(target_name)
2919
+ info = toolchain.find_compiler(spec)
2920
+ zig = None
2921
+ if info is None:
2922
+ zig = toolchain.find_zig()
2923
+ if info is None and zig is None:
2924
+ raise toolchain.ToolchainError(toolchain.hint(spec))
2925
+ source = emit_c(instructions, labels, segments, entry_pc, mem_size, sp,
2926
+ heap_base)
2927
+ out = os.path.abspath(out)
2928
+ if spec.exe and not out.lower().endswith(spec.exe):
2929
+ out += spec.exe
2930
+ os.makedirs(os.path.dirname(out) or '.', exist_ok=True)
2931
+ workdir = tempfile.mkdtemp(prefix='.aotc-')
2932
+ try:
2933
+ c_path = os.path.join(workdir, 'program.c')
2934
+ with open(c_path, 'w', encoding='utf-8', newline='\n') as f:
2935
+ f.write(source)
2936
+ if keep_c:
2937
+ import shutil
2938
+ shutil.copyfile(c_path, out + '.c')
2939
+ if info is not None:
2940
+ cmd = [info.path, f'-O{max(0, min(3, int(optimize)))}',
2941
+ '-std=c11', '-o', out, c_path]
2942
+ else:
2943
+ # Zig 自带目标平台 libc, 无需交叉 sysroot
2944
+ cmd = [zig, 'cc', '-target', spec.triple,
2945
+ '-D_DEFAULT_SOURCE', '-D_GNU_SOURCE',
2946
+ '-D_POSIX_C_SOURCE=200809L',
2947
+ f'-O{max(0, min(3, int(optimize)))}',
2948
+ '-std=c11', '-o', out, c_path]
2949
+ if static_link and spec.fmt != 'macho':
2950
+ cmd.append('-static') # macOS 不支持静态链接 libSystem
2951
+ if strip_binary:
2952
+ cmd.append('-s') # 去掉符号表, 减小体积
2953
+ if spec.fmt != 'pe':
2954
+ cmd.append('-lm') # Linux/ELF 的 libm 需显式链接
2955
+ else:
2956
+ cmd.append('-lws2_32') # Windows 的 Winsock
2957
+ try:
2958
+ result = subprocess.run(cmd, capture_output=True, text=True,
2959
+ timeout=600, check=False)
2960
+ except (OSError, subprocess.SubprocessError) as e:
2961
+ raise CBackendError(f'调用 C 编译器失败: {e}') from e
2962
+ if result.returncode != 0:
2963
+ raise CBackendError(
2964
+ f'C 编译失败 ({"zig cc" if info is None else info.path}):\n'
2965
+ f'{(result.stderr or result.stdout).strip()[:4000]}')
2966
+ finally:
2967
+ import shutil
2968
+ shutil.rmtree(workdir, ignore_errors=True)
2969
+ return out
2970
+
2971
+
2972
+ def _host_target_name() -> str:
2973
+ import platform
2974
+ system = platform.system()
2975
+ machine = platform.machine().lower()
2976
+ if system == 'Windows':
2977
+ return 'x86_64-windows'
2978
+ if machine in ('arm64', 'aarch64'):
2979
+ return 'aarch64-linux'
2980
+ return 'x86_64-linux'
2981
+
2982
+
2983
+ def c_target(goos: str, goarch: str = 'amd64') -> str:
2984
+ """把 AOT 的 (GOOS, GOARCH) 映射成 C 后端目标名。"""
2985
+ goos = (goos or '').lower()
2986
+ goarch = (goarch or 'amd64').lower()
2987
+ if goos == 'windows' and goarch in ('amd64', 'x86_64'):
2988
+ return 'x86_64-windows'
2989
+ if goos == 'linux':
2990
+ if goarch in ('arm64', 'aarch64'):
2991
+ return 'aarch64-linux'
2992
+ if goarch in ('arm', 'armv7'):
2993
+ return 'arm-linux'
2994
+ if goarch in ('riscv64', 'riscv'):
2995
+ return 'riscv64-linux'
2996
+ return 'x86_64-linux'
2997
+ raise CBackendError(
2998
+ f'C 后端暂不支持目标 {goos}/{goarch} (可选: windows/amd64, '
2999
+ f'linux/amd64, linux/arm64, linux/arm, linux/riscv64)')
3000
+
3001
+
3002
+ def _syscall_name(code: int) -> str:
3003
+ try:
3004
+ from .isa import Syscall
3005
+ return Syscall(code).name
3006
+ except (ValueError, ImportError):
3007
+ return f'SYS{code}'
3008
+
3009
+
3010
+ def supports(instructions: Sequence[Instruction]) -> Tuple[bool, str]:
3011
+ """指令流能否由 C 后端完整翻译; 不支持时返回原因。"""
3012
+ missing = sorted({str(op) for op, _args in instructions
3013
+ if str(op) not in SUPPORTED_OPS})
3014
+ if missing:
3015
+ return False, '未实现的指令: ' + ', '.join(missing)
3016
+ for op, args in instructions:
3017
+ if str(op) != 'SYS' or not args:
3018
+ continue
3019
+ if args[0][0] != 'imm':
3020
+ return False, 'SYS 功能号必须是常量'
3021
+ code = int(args[0][1])
3022
+ if code not in SUPPORTED_SYS:
3023
+ return False, f'未实现的 SYS {code} ({_syscall_name(code)})'
3024
+ return True, ''