-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolymorphicCode
More file actions
63 lines (55 loc) · 2.04 KB
/
Copy pathPolymorphicCode
File metadata and controls
63 lines (55 loc) · 2.04 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
#!/usr/bin/env python3
"""
A minimal demonstration of polymorphic code in Python:
- On first launch, reads its own source.
- Applies simple mutation rules to arithmetic expressions.
- Writes out a mutated copy and re‐executes it.
- When run in “mutated” mode, performs the core algorithm.
Each mutation produces different machine code at run time
while preserving the same semantics (here: computing 3+1).
"""
import sys, os, re, random
MUTATION_FLAG = "--mutated"
# === Core functionality ===
def core():
# This is the “payload” whose semantics we preserve.
result = 3 + 1
print(f"[{os.path.basename(__file__)}] Result is {result}")
# === Polymorphic engine ===
def load_source():
"""Read and return this file’s own source."""
with open(__file__, 'r', encoding='utf-8') as f:
return f.read()
def mutate_expression(src):
"""
Find one occurrence of '3 + 1' and replace it
with a random semantically equivalent expression.
"""
# List of equivalent expressions for 3+1
equivalents = ["6 - 2", "2 * 2", "8 / 2", "5 - 1", "1 + 3"]
# Regex to match the literal '3 + 1' (with optional spaces)
pattern = re.compile(r"\b3\s*\+\s*1\b")
if pattern.search(src):
replacement = random.choice(equivalents)
# Replace only the first instance
src = pattern.sub(replacement, src, count=1)
return src
def write_and_exec(new_src):
"""Write mutated source to a temp file and re‐exec it."""
tmp_path = __file__ + ".tmp.py"
with open(tmp_path, 'w', encoding='utf-8') as f:
f.write(new_src)
# Mark it so we don’t loop infinitely
os.execv(sys.executable, [sys.executable, tmp_path, MUTATION_FLAG])
# === Entrypoint ===
if __name__ == "__main__":
# If we’re already in mutated mode, just run the core.
if MUTATION_FLAG in sys.argv:
core()
else:
# 1) Load our own code
src = load_source()
# 2) Mutate it
new_src = mutate_expression(src)
# 3) Write out and re‐execute
write_and_exec(new_src)