This repository was archived by the owner on Aug 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathrand_opcodes.lua
More file actions
103 lines (74 loc) · 2.47 KB
/
rand_opcodes.lua
File metadata and controls
103 lines (74 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/env lua
local function readfile(name)
local f = assert(io.open(name, "r"))
local c = f:read("*a")
f:close()
return c
end
local function writefile(name, content)
assert(content)
local f = assert(io.open(name, "w"))
f:write(content)
f:close()
end
assert((...))
local source_dir = string.gsub((...), "/$", "")
local h = readfile(source_dir .. "/lopcodes.h")
local c = readfile(source_dir .. "/lopcodes.c")
local op_mapped = {}
local last_opcode
local function mapped(list, f)
assert(#list == #op_mapped)
local t = {}
for _, i in ipairs(op_mapped) do
table.insert(t, assert(f and f(list[i]) or list[i]))
end
return t
end
math.randomseed(os.time())
-- replace lopcodes.h ---------------------------------------------------------
local h2 = string.gsub(h, "typedef enum {(.*)} OpCode;", function(s)
local opcodes = {}
for m in string.gmatch(s, "(OP_%u+),?") do
table.insert(opcodes, m)
end
local t = {}
for i=1, #opcodes do
table.insert(t, i)
end
for i=1, #opcodes do
local index = math.random (1, #t)
table.insert(op_mapped, t[index])
table.remove(t, index)
end
local new_opcodes = mapped(opcodes)
last_opcode = new_opcodes[#new_opcodes]
return "typedef enum {\n" .. table.concat(new_opcodes, ",\n") .. "\n} OpCode;"
end, 1)
assert(h ~= h2, "failed to replace opcode")
local h_final = string.gsub(h2, "NUM_OPCODES%c%(cast%(int, (OP_%u+)%) %+ 1%)", function(s)
return string.format("NUM_OPCODES (cast(int, %s) + 1)", last_opcode)
end, 1)
assert(#op_mapped > 0)
-- replace lopcodes.c ---------------------------------------------------------
local c2 = string.gsub(c, "{(.*)NULL%c};", function(s)
local opstrs = {}
for m in string.gmatch(s, "\"(%u+)\",") do
table.insert(opstrs, m)
end
return "{\n" .. table.concat(mapped(opstrs, function (s)
return " \"" .. s .. "\","
end), "\n") .. "\n NULL\n};"
end)
assert(c ~= c2, "failed to replace opstrs")
local c_final = string.gsub(c2, "luaP_opmodes%[NUM_OPCODES%] = {(.*)}", function(s)
local opmodes = {}
for m in string.gmatch(s, "opmode%([^(^)]+%)") do
table.insert(opmodes, m)
end
return "luaP_opmodes[NUM_OPCODES] = {\n " ..
table.concat(mapped(opmodes), "\n ,") .. "\n}"
end)
assert(c2 ~= c_final, "failed to replace opmodes")
writefile(source_dir .. "/lopcodes.h", h_final)
writefile(source_dir .. "/lopcodes.c", c_final)