janky-jit 1.0.0__tar.gz

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.
@@ -0,0 +1,206 @@
1
+ Metadata-Version: 2.4
2
+ Name: janky-jit
3
+ Version: 1.0.0
4
+ Summary: Hyper-optimized, multi-language polyglot JIT framework for Python.
5
+ Author: Adam
6
+ Classifier: Development Status :: 5 - Production/Stable
7
+ Classifier: Intended Audience :: Developers
8
+ Classifier: Topic :: Software Development :: Compilers
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: POSIX :: Linux
11
+ Requires-Python: >=3.7
12
+ Description-Content-Type: text/markdown
13
+ Provides-Extra: systems
14
+ Provides-Extra: zig
15
+ Provides-Extra: nim
16
+ Provides-Extra: all
17
+ Dynamic: author
18
+ Dynamic: classifier
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: provides-extra
22
+ Dynamic: requires-python
23
+ Dynamic: summary
24
+
25
+ # 🏗️ Janky
26
+
27
+ > It is not a bug, it is architectural dominance.
28
+
29
+ Janky is a hyper-optimized, native compilation polyglot JIT framework for Python. It allows you to embed raw **Assembly (64-bit and retro 32-bit), C++, Rust, Zig (Jig), Pure C, Nim, Raw Machine Code Hex Strings (Jinary), and Brainfuck** source strings directly within your Python scripts, compilation-cached via OpenSSL SHA-256 fingerprinting, and executed at bare-metal speeds with zero abstraction overhead.
30
+
31
+ The core C compilation engines are secured behind an absolute systems-level Linux virtual filesystem lock (`chattr +i`). Janky bypasses Python's runtime limitations by loading compiled `.so` binaries directly into active memory using `dlopen` or mapping execution blocks natively into memory via `mprotect`.
32
+
33
+ ---
34
+
35
+ ## 🚀 The Native Core Lineup
36
+
37
+ | Extension | Language | Backend Toolchain | Best Used For | Boilerplate Magic |
38
+ | --- | --- | --- | --- | --- |
39
+ | `jasm` | x86-64 Assembly | `nasm` | Raw register control, vector ops | Pure `sysv` ABI assembly |
40
+ | `jasm86` | 32-bit x86 Assembly | `nasm` | Stack-based legacy shellcode hacking | 32-bit memory sandbox execution |
41
+ | `jcpp` | C++ | `g++` | Heavy OOP, Matrix math, game physics | Requires `extern "C"` linkage |
42
+ | `just` | Rust | `rustc` | Memory-safe pipelines, hyper-threading | Requires `#[no_mangle] pub extern "C"` |
43
+ | `jig` | Zig | `zig` | Ultra-modern, low-overhead algorithms | Requires `export fn` notation |
44
+ | `jc` | Pure C | `gcc` / `clang` | Fastest cold compilation, retro tasks | Native C symbol preservation |
45
+ | `jnim` | Nim | `nim` | Python-like syntax at bare-metal speeds | Requires `{.exportc, cdecl.}` |
46
+ | `jinary` | Raw Binary Hex | `mprotect` Runtime | Direct execution of raw opcode arrays | Requires raw x86-64 executable hex |
47
+ | `jbrainfuck` | Brainfuck | Native JIT Gen | Melting-fast esoteric logic execution | Emits optimized x86-64 opcodes directly |
48
+
49
+ ---
50
+
51
+ ## 💾 Installation & Setup
52
+
53
+ ### 1. Install System Dependencies
54
+
55
+ Ensure your machine is weaponized with the required system compilers:
56
+
57
+ ```bash
58
+ # Core Build Tools & OpenSSL development headers
59
+ sudo apt update
60
+ sudo apt install build-essential nasm libssl-dev
61
+
62
+ # Modern Compiler Ecosystem
63
+ sudo apt install zig nim
64
+ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
65
+
66
+ ```
67
+
68
+ ### 2. Compile the Janky Extension Matrix
69
+
70
+ Navigate to your project directory, activate your virtual environment, and fire the build:
71
+
72
+ ```bash
73
+ # Clean out any old stale build artifacts
74
+ rm -rf build/
75
+
76
+ # Compile and register all 9 native extension wrappers
77
+ pip install .
78
+
79
+ ```
80
+
81
+ ### 3. Seal the Fortress 🔒
82
+
83
+ Protect your foundational compiler engines from accidental edits or late-night programming accidents by locking them directly into the Linux Kernel space:
84
+
85
+ ```bash
86
+ sudo chattr -R +i janky/compiler
87
+
88
+ ```
89
+
90
+ *Note: If you ever need to upgrade the core engines, lift the spell with `sudo chattr -R -i janky/compiler`.*
91
+
92
+ ---
93
+
94
+ ## 🎸 Quick Start Tour (Polyglot Blitz)
95
+
96
+ You can now import and utilize **any** low-level native engine from anywhere on your machine as long as your virtual environment is active!
97
+
98
+ ```python
99
+ import time
100
+ from janky.compiler import jasm, just, jig, jc, jnim, jinary, jbrainfuck
101
+
102
+ # ==============================================================================
103
+ # 1. JINARY (Raw Executable Machine Code Opcodes)
104
+ # ==============================================================================
105
+ # Raw hex bytes for: mov rax, rdi (48 89 f8); add rax, rsi (48 01 f0); ret (c3)
106
+ hex_code = "4889f84801f0c3"
107
+ jinary_engine = jinary.compile(hex_code, "raw_exec")
108
+ print(f"Jinary Machine Code Add: {jinary_engine(20, 22)}") # 42
109
+
110
+
111
+ # ==============================================================================
112
+ # 2. BRAINFUCK (Natively Optimized JIT Compiler)
113
+ # ==============================================================================
114
+ bf_code = "++++++++++[>+++++++>++++++++++<<-]>++.>+.[-]"
115
+ jbf_engine = jbrainfuck.compile(bf_code, "bf_run")
116
+ tape = bytearray(30000)
117
+ print("Executing JIT Brainfuck:")
118
+ jbf_engine(tape) # Prints 'Hi' directly via optimized native write syscalls
119
+
120
+
121
+ # ==============================================================================
122
+ # 3. PURE C (Fastest Cold Compile)
123
+ # ==============================================================================
124
+ c_code = """
125
+ #include <stdint.h>
126
+ uint64_t c_factorial(uint64_t n) {
127
+ return (n <= 1) ? 1 : n * c_factorial(n - 1);
128
+ }
129
+ """
130
+ jc_engine = jc.compile(c_code, "c_factorial")
131
+ print(f"Pure C Factorial(5): {jc_engine(5)}") # 120
132
+
133
+
134
+ # ==============================================================================
135
+ # 4. RUST (Memory Safe & Optimizing)
136
+ # ==============================================================================
137
+ rust_code = """
138
+ #[no_mangle]
139
+ pub extern "C" fn rust_cube(x: u64) -> u64 {
140
+ x * x * x
141
+ }
142
+ """
143
+ rust_engine = just.compile(rust_code, "rust_cube")
144
+ print(f"Rust Cube(3): {rust_engine(3)}") # 27
145
+
146
+
147
+ # ==============================================================================
148
+ # 5. ZIG / JIG (Modern & Transparent)
149
+ # ==============================================================================
150
+ zig_code = """
151
+ export fn zig_xor(a: u64, b: u64) u64 {
152
+ return a ^ b;
153
+ }
154
+ """
155
+ jig_engine = jig.compile(zig_code, "zig_xor")
156
+ print(f"Zig Bitwise XOR: {jig_engine(1024, 1)}") # 1025
157
+
158
+
159
+ # ==============================================================================
160
+ # 6. NIM (Pythonic Syntax, C Execution Speed)
161
+ # ==============================================================================
162
+ nim_code = """
163
+ proc nim_fib(n: int64): int64 {.exportc, cdecl.} =
164
+ if n <= 1: return n
165
+ else: return nim_fib(n - 1) + nim_fib(n - 2)
166
+ """
167
+ jnim_engine = jnim.compile(nim_code, "nim_fib")
168
+ print(f"Nim Fibonacci(10): {jnim_engine(10)}") # 55
169
+
170
+
171
+ # ==============================================================================
172
+ # 7. X86-64 ASSEMBLY (Ultimate Control)
173
+ # ==============================================================================
174
+ asm_code = """
175
+ global asm_add
176
+ section .text
177
+ asm_add:
178
+ mov rax, rdi ; rdi is first argument (a)
179
+ add rax, rsi ; rsi is second argument (b)
180
+ ret ; Return value stored in rax
181
+ """
182
+ jasm_engine = jasm.compile(asm_code, "asm_add")
183
+ print(f"Raw Assembly Add: {jasm_engine(40, 2)}") # 42
184
+
185
+ ```
186
+
187
+ ---
188
+
189
+ ## 🛠️ Performance & Architecture
190
+
191
+ Every time you execute a `.compile()` string across any language module:
192
+
193
+ 1. **Fingerprinting:** Janky hashes the source code token string using OpenSSL SHA-256.
194
+ 2. **Hit Detection:** If the hash exists inside the `.janky_cache/` directory, the compiler execution is completely skipped, instantly performing a high-speed `dlopen` read on the pre-compiled `.so` block or reusing memory allocated regions.
195
+ 3. **Arguments Passthrough:** Up to 6 standard integer variables or direct **raw memory block pointer addresses** (via Python's buffer protocol) can be funneled directly into function parameters with **zero serialization penalty**.
196
+
197
+ ## 🛑 Project Boundaries / Guardrails
198
+
199
+ * **Do not modify `janky/compiler/` contents.** The kernel will throw a hard `Operation not permitted`.
200
+ * **Argument Constraint:** Maximum of 6 arguments map natively to system registers under the current C calling architecture wrapper.
201
+
202
+ ---
203
+
204
+ ## 📜 License
205
+
206
+ Unlicensed. Pure hacking freedom. Go break some memory limits.
@@ -0,0 +1,182 @@
1
+ # 🏗️ Janky
2
+
3
+ > It is not a bug, it is architectural dominance.
4
+
5
+ Janky is a hyper-optimized, native compilation polyglot JIT framework for Python. It allows you to embed raw **Assembly (64-bit and retro 32-bit), C++, Rust, Zig (Jig), Pure C, Nim, Raw Machine Code Hex Strings (Jinary), and Brainfuck** source strings directly within your Python scripts, compilation-cached via OpenSSL SHA-256 fingerprinting, and executed at bare-metal speeds with zero abstraction overhead.
6
+
7
+ The core C compilation engines are secured behind an absolute systems-level Linux virtual filesystem lock (`chattr +i`). Janky bypasses Python's runtime limitations by loading compiled `.so` binaries directly into active memory using `dlopen` or mapping execution blocks natively into memory via `mprotect`.
8
+
9
+ ---
10
+
11
+ ## 🚀 The Native Core Lineup
12
+
13
+ | Extension | Language | Backend Toolchain | Best Used For | Boilerplate Magic |
14
+ | --- | --- | --- | --- | --- |
15
+ | `jasm` | x86-64 Assembly | `nasm` | Raw register control, vector ops | Pure `sysv` ABI assembly |
16
+ | `jasm86` | 32-bit x86 Assembly | `nasm` | Stack-based legacy shellcode hacking | 32-bit memory sandbox execution |
17
+ | `jcpp` | C++ | `g++` | Heavy OOP, Matrix math, game physics | Requires `extern "C"` linkage |
18
+ | `just` | Rust | `rustc` | Memory-safe pipelines, hyper-threading | Requires `#[no_mangle] pub extern "C"` |
19
+ | `jig` | Zig | `zig` | Ultra-modern, low-overhead algorithms | Requires `export fn` notation |
20
+ | `jc` | Pure C | `gcc` / `clang` | Fastest cold compilation, retro tasks | Native C symbol preservation |
21
+ | `jnim` | Nim | `nim` | Python-like syntax at bare-metal speeds | Requires `{.exportc, cdecl.}` |
22
+ | `jinary` | Raw Binary Hex | `mprotect` Runtime | Direct execution of raw opcode arrays | Requires raw x86-64 executable hex |
23
+ | `jbrainfuck` | Brainfuck | Native JIT Gen | Melting-fast esoteric logic execution | Emits optimized x86-64 opcodes directly |
24
+
25
+ ---
26
+
27
+ ## 💾 Installation & Setup
28
+
29
+ ### 1. Install System Dependencies
30
+
31
+ Ensure your machine is weaponized with the required system compilers:
32
+
33
+ ```bash
34
+ # Core Build Tools & OpenSSL development headers
35
+ sudo apt update
36
+ sudo apt install build-essential nasm libssl-dev
37
+
38
+ # Modern Compiler Ecosystem
39
+ sudo apt install zig nim
40
+ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
41
+
42
+ ```
43
+
44
+ ### 2. Compile the Janky Extension Matrix
45
+
46
+ Navigate to your project directory, activate your virtual environment, and fire the build:
47
+
48
+ ```bash
49
+ # Clean out any old stale build artifacts
50
+ rm -rf build/
51
+
52
+ # Compile and register all 9 native extension wrappers
53
+ pip install .
54
+
55
+ ```
56
+
57
+ ### 3. Seal the Fortress 🔒
58
+
59
+ Protect your foundational compiler engines from accidental edits or late-night programming accidents by locking them directly into the Linux Kernel space:
60
+
61
+ ```bash
62
+ sudo chattr -R +i janky/compiler
63
+
64
+ ```
65
+
66
+ *Note: If you ever need to upgrade the core engines, lift the spell with `sudo chattr -R -i janky/compiler`.*
67
+
68
+ ---
69
+
70
+ ## 🎸 Quick Start Tour (Polyglot Blitz)
71
+
72
+ You can now import and utilize **any** low-level native engine from anywhere on your machine as long as your virtual environment is active!
73
+
74
+ ```python
75
+ import time
76
+ from janky.compiler import jasm, just, jig, jc, jnim, jinary, jbrainfuck
77
+
78
+ # ==============================================================================
79
+ # 1. JINARY (Raw Executable Machine Code Opcodes)
80
+ # ==============================================================================
81
+ # Raw hex bytes for: mov rax, rdi (48 89 f8); add rax, rsi (48 01 f0); ret (c3)
82
+ hex_code = "4889f84801f0c3"
83
+ jinary_engine = jinary.compile(hex_code, "raw_exec")
84
+ print(f"Jinary Machine Code Add: {jinary_engine(20, 22)}") # 42
85
+
86
+
87
+ # ==============================================================================
88
+ # 2. BRAINFUCK (Natively Optimized JIT Compiler)
89
+ # ==============================================================================
90
+ bf_code = "++++++++++[>+++++++>++++++++++<<-]>++.>+.[-]"
91
+ jbf_engine = jbrainfuck.compile(bf_code, "bf_run")
92
+ tape = bytearray(30000)
93
+ print("Executing JIT Brainfuck:")
94
+ jbf_engine(tape) # Prints 'Hi' directly via optimized native write syscalls
95
+
96
+
97
+ # ==============================================================================
98
+ # 3. PURE C (Fastest Cold Compile)
99
+ # ==============================================================================
100
+ c_code = """
101
+ #include <stdint.h>
102
+ uint64_t c_factorial(uint64_t n) {
103
+ return (n <= 1) ? 1 : n * c_factorial(n - 1);
104
+ }
105
+ """
106
+ jc_engine = jc.compile(c_code, "c_factorial")
107
+ print(f"Pure C Factorial(5): {jc_engine(5)}") # 120
108
+
109
+
110
+ # ==============================================================================
111
+ # 4. RUST (Memory Safe & Optimizing)
112
+ # ==============================================================================
113
+ rust_code = """
114
+ #[no_mangle]
115
+ pub extern "C" fn rust_cube(x: u64) -> u64 {
116
+ x * x * x
117
+ }
118
+ """
119
+ rust_engine = just.compile(rust_code, "rust_cube")
120
+ print(f"Rust Cube(3): {rust_engine(3)}") # 27
121
+
122
+
123
+ # ==============================================================================
124
+ # 5. ZIG / JIG (Modern & Transparent)
125
+ # ==============================================================================
126
+ zig_code = """
127
+ export fn zig_xor(a: u64, b: u64) u64 {
128
+ return a ^ b;
129
+ }
130
+ """
131
+ jig_engine = jig.compile(zig_code, "zig_xor")
132
+ print(f"Zig Bitwise XOR: {jig_engine(1024, 1)}") # 1025
133
+
134
+
135
+ # ==============================================================================
136
+ # 6. NIM (Pythonic Syntax, C Execution Speed)
137
+ # ==============================================================================
138
+ nim_code = """
139
+ proc nim_fib(n: int64): int64 {.exportc, cdecl.} =
140
+ if n <= 1: return n
141
+ else: return nim_fib(n - 1) + nim_fib(n - 2)
142
+ """
143
+ jnim_engine = jnim.compile(nim_code, "nim_fib")
144
+ print(f"Nim Fibonacci(10): {jnim_engine(10)}") # 55
145
+
146
+
147
+ # ==============================================================================
148
+ # 7. X86-64 ASSEMBLY (Ultimate Control)
149
+ # ==============================================================================
150
+ asm_code = """
151
+ global asm_add
152
+ section .text
153
+ asm_add:
154
+ mov rax, rdi ; rdi is first argument (a)
155
+ add rax, rsi ; rsi is second argument (b)
156
+ ret ; Return value stored in rax
157
+ """
158
+ jasm_engine = jasm.compile(asm_code, "asm_add")
159
+ print(f"Raw Assembly Add: {jasm_engine(40, 2)}") # 42
160
+
161
+ ```
162
+
163
+ ---
164
+
165
+ ## 🛠️ Performance & Architecture
166
+
167
+ Every time you execute a `.compile()` string across any language module:
168
+
169
+ 1. **Fingerprinting:** Janky hashes the source code token string using OpenSSL SHA-256.
170
+ 2. **Hit Detection:** If the hash exists inside the `.janky_cache/` directory, the compiler execution is completely skipped, instantly performing a high-speed `dlopen` read on the pre-compiled `.so` block or reusing memory allocated regions.
171
+ 3. **Arguments Passthrough:** Up to 6 standard integer variables or direct **raw memory block pointer addresses** (via Python's buffer protocol) can be funneled directly into function parameters with **zero serialization penalty**.
172
+
173
+ ## 🛑 Project Boundaries / Guardrails
174
+
175
+ * **Do not modify `janky/compiler/` contents.** The kernel will throw a hard `Operation not permitted`.
176
+ * **Argument Constraint:** Maximum of 6 arguments map natively to system registers under the current C calling architecture wrapper.
177
+
178
+ ---
179
+
180
+ ## 📜 License
181
+
182
+ Unlicensed. Pure hacking freedom. Go break some memory limits.
@@ -0,0 +1 @@
1
+ from . import compiler
@@ -0,0 +1,10 @@
1
+ # janky/compiler/__init__.py
2
+ from .. import jasm
3
+ from .. import jasm86
4
+ from .. import jcpp
5
+ from .. import just
6
+ from .. import jig
7
+ from .. import jc
8
+ from .. import jnim
9
+ from .. import jinary
10
+ from .. import jbrainfuck # New!
@@ -0,0 +1,218 @@
1
+ #define PY_SSIZE_T_CLEAN
2
+ #include <Python.h>
3
+ #include <string.h>
4
+ #include <sys/mman.h>
5
+ #include <stdio.h>
6
+ #include <stdlib.h>
7
+ #include <unistd.h>
8
+ #include <stdint.h>
9
+
10
+ // Helper to read files safely
11
+ unsigned char *read_file(const char *filename, size_t *out_size) {
12
+ FILE *f = fopen(filename, "rb");
13
+ if (!f) return NULL;
14
+
15
+ fseek(f, 0, SEEK_END);
16
+ long size = ftell(f);
17
+ fseek(f, 0, SEEK_SET);
18
+
19
+ if (size <= 0) {
20
+ fclose(f);
21
+ return NULL;
22
+ }
23
+
24
+ unsigned char *data = (unsigned char *)malloc(size);
25
+ if (!data) {
26
+ fclose(f);
27
+ return NULL;
28
+ }
29
+
30
+ size_t read_bytes = fread(data, 1, size, f);
31
+ fclose(f);
32
+
33
+ *out_size = read_bytes;
34
+ return data;
35
+ }
36
+
37
+ // Helper to read NASM build errors and raise them inside Python
38
+ static void raise_nasm_error(const char *err_file) {
39
+ size_t err_size = 0;
40
+ unsigned char *err_data = read_file(err_file, &err_size);
41
+ if (err_data && err_size > 0) {
42
+ // Null terminate the error log safely
43
+ char *err_msg = malloc(err_size + 1);
44
+ if (err_msg) {
45
+ memcpy(err_msg, err_data, err_size);
46
+ err_msg[err_size] = '\0';
47
+ PyErr_Format(PyExc_SyntaxError, "NASM compilation failed:\n%s", err_msg);
48
+ free(err_msg);
49
+ } else {
50
+ PyErr_SetString(PyExc_SyntaxError, "NASM compilation failed (out of memory reading logs).");
51
+ }
52
+ free(err_data);
53
+ } else {
54
+ PyErr_SetString(PyExc_SyntaxError, "NASM compilation failed with unknown syntax errors.");
55
+ }
56
+ }
57
+
58
+ typedef struct {
59
+ PyObject_HEAD
60
+ unsigned char *code;
61
+ size_t code_size;
62
+ } AssemblyFunction;
63
+
64
+ static void AssemblyFunction_dealloc(AssemblyFunction *self) {
65
+ if (self->code) {
66
+ munmap(self->code, self->code_size);
67
+ }
68
+ Py_TYPE(self)->tp_free((PyObject *)self);
69
+ }
70
+
71
+ static PyObject *AssemblyFunction_call(AssemblyFunction *self, PyObject *args, PyObject *kwargs) {
72
+ Py_ssize_t nargs = PyTuple_Size(args);
73
+ if (nargs > 6) {
74
+ PyErr_SetString(PyExc_ValueError, "System V AMD64 ABI supports a max of 6 register arguments");
75
+ return NULL;
76
+ }
77
+
78
+ uint64_t call_args[6] = {0};
79
+
80
+ for (Py_ssize_t i = 0; i < nargs; i++) {
81
+ PyObject *item = PyTuple_GetItem(args, i);
82
+
83
+ // If it's an integer, pass it raw
84
+ if (PyLong_Check(item)) {
85
+ call_args[i] = (uint64_t)PyLong_AsUnsignedLongLong(item);
86
+ if (PyErr_Occurred()) return NULL;
87
+ }
88
+ // If it supports the Buffer Protocol (bytes, bytearray, memoryview), pass its raw memory pointer!
89
+ else if (PyObject_CheckBuffer(item)) {
90
+ Py_buffer view;
91
+ if (PyObject_GetBuffer(item, &view, PyBUF_SIMPLE) == 0) {
92
+ call_args[i] = (uint64_t)view.buf;
93
+ PyBuffer_Release(&view); // Release the view handle, but the pointer address remains valid during call
94
+ } else {
95
+ PyErr_SetString(PyExc_TypeError, "Failed to extract buffer pointer");
96
+ return NULL;
97
+ }
98
+ } else {
99
+ PyErr_SetString(PyExc_TypeError, "Arguments must be integers or buffer-like objects (bytes/bytearray).");
100
+ return NULL;
101
+ }
102
+ }
103
+
104
+ // Pure execution mapping directly to standard System V ABI calling convention:
105
+ // rdi, rsi, rdx, rcx, r8, r9
106
+ uint64_t (*func)(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t, uint64_t) =
107
+ (uint64_t (*)(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t, uint64_t))(self->code);
108
+
109
+ // Execute raw hardware thread!
110
+ uint64_t result = func(call_args[0], call_args[1], call_args[2],
111
+ call_args[3], call_args[4], call_args[5]);
112
+
113
+ return PyLong_FromUnsignedLongLong(result);
114
+ }
115
+
116
+ static PyTypeObject AssemblyFunctionType = {
117
+ PyVarObject_HEAD_INIT(NULL, 0)
118
+ .tp_name = "janky.AssemblyFunction",
119
+ .tp_basicsize = sizeof(AssemblyFunction),
120
+ .tp_dealloc = (destructor)AssemblyFunction_dealloc,
121
+ .tp_call = (ternaryfunc)AssemblyFunction_call,
122
+ .tp_flags = Py_TPFLAGS_DEFAULT,
123
+ .tp_doc = "Callable raw assembly function",
124
+ };
125
+
126
+ static PyObject *compile_asm(PyObject *self, PyObject *args) {
127
+ const char *asm_code;
128
+ if (!PyArg_ParseTuple(args, "s", &asm_code)) return NULL;
129
+
130
+ const char *asm_file = "/tmp/janky_temp.asm";
131
+ const char *obj_file = "/tmp/janky_temp.o";
132
+ const char *err_file = "/tmp/janky_error.txt";
133
+
134
+ FILE *f = fopen(asm_file, "w");
135
+ if (!f) { PyErr_SetString(PyExc_RuntimeError, "Cannot write temporary assembly file"); return NULL; }
136
+
137
+ // We strictly specify BITS 64, nothing else. The user writes clean, pure, unrestricted assembly.
138
+ fprintf(f, "BITS 64\n");
139
+ fprintf(f, "%s\n", asm_code);
140
+ fclose(f);
141
+
142
+ char cmd[1024];
143
+ snprintf(cmd, sizeof(cmd), "nasm -f bin -o %s %s 2>%s", obj_file, asm_file, err_file);
144
+ if (system(cmd) != 0) {
145
+ raise_nasm_error(err_file);
146
+ unlink(asm_file);
147
+ unlink(obj_file);
148
+ unlink(err_file);
149
+ return NULL;
150
+ }
151
+
152
+ size_t code_size = 0;
153
+ unsigned char *code_bytes = read_file(obj_file, &code_size);
154
+
155
+ unlink(asm_file);
156
+ unlink(obj_file);
157
+ unlink(err_file);
158
+
159
+ if (!code_bytes || code_size == 0) {
160
+ PyErr_SetString(PyExc_RuntimeError, "Compiled binary was empty or corrupt.");
161
+ return NULL;
162
+ }
163
+
164
+ // Allocate page-aligned memory
165
+ unsigned char *exec_mem = mmap(NULL, code_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
166
+ if (exec_mem == MAP_FAILED) {
167
+ free(code_bytes);
168
+ PyErr_SetString(PyExc_RuntimeError, "mmap mapping execution space failed");
169
+ return NULL;
170
+ }
171
+
172
+ memcpy(exec_mem, code_bytes, code_size);
173
+ free(code_bytes);
174
+
175
+ // Swap permissions to strictly Read + Execute (W^X security adherence)
176
+ if (mprotect(exec_mem, code_size, PROT_READ | PROT_EXEC) == -1) {
177
+ munmap(exec_mem, code_size);
178
+ PyErr_SetString(PyExc_RuntimeError, "mprotect memory lockdown failed");
179
+ return NULL;
180
+ }
181
+
182
+ AssemblyFunction *func_obj = PyObject_New(AssemblyFunction, &AssemblyFunctionType);
183
+ if (!func_obj) {
184
+ munmap(exec_mem, code_size);
185
+ return NULL;
186
+ }
187
+ func_obj->code = exec_mem;
188
+ func_obj->code_size = code_size;
189
+ return (PyObject *)func_obj;
190
+ }
191
+
192
+ static PyMethodDef JasmMethods[] = {
193
+ {"compile", compile_asm, METH_VARARGS, "Compile raw x86-64 assembly using NASM"},
194
+ {NULL, NULL, 0, NULL}
195
+ };
196
+
197
+ static struct PyModuleDef jasm_module = {
198
+ PyModuleDef_HEAD_INIT,
199
+ "jasm",
200
+ "Full raw x86-64 assembly injection engine for Python",
201
+ -1,
202
+ JasmMethods
203
+ };
204
+
205
+ PyMODINIT_FUNC PyInit_jasm(void) {
206
+ PyObject *m = PyModule_Create(&jasm_module);
207
+ if (!m) return NULL;
208
+ if (PyType_Ready(&AssemblyFunctionType) < 0) return NULL;
209
+
210
+ // Modernized Python 3.10+ safe reference addition
211
+ Py_INCREF(&AssemblyFunctionType);
212
+ if (PyModule_AddObject(m, "AssemblyFunction", (PyObject *)&AssemblyFunctionType) < 0) {
213
+ Py_DECREF(&AssemblyFunctionType);
214
+ Py_DECREF(m);
215
+ return NULL;
216
+ }
217
+ return m;
218
+ }