[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-111358":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":15,"subscribersCount":15,"size":15,"stars1d":15,"stars7d":14,"stars30d":16,"stars90d":15,"forks30d":15,"starsTrendScore":17,"compositeScore":18,"rankGlobal":10,"rankLanguage":10,"license":10,"archived":19,"fork":19,"defaultBranch":20,"hasWiki":19,"hasPages":19,"topics":21,"createdAt":10,"pushedAt":22,"updatedAt":23,"readmeContent":24,"aiSummary":25,"trendingCount":15,"starSnapshotCount":15,"syncStatus":14,"lastSyncTime":26,"discoverSource":27},111358,"MemLLVM","Laster-dev\u002FMemLLVM","Laster-dev","An unrestricted shellcode compiler for c\u002Fc++ based on llvm","",null,"C",63,27,2,0,12,1,43.54,false,"master",[],"2026-11-07 06:23:22","2026-11-22 10:40:01","# MemLLVM\n\n\u003Cdiv align=\"center\">\n\n# ⚡ MemLLVM\n### Next-Generation LLVM Pass Plugin & Freestanding C\u002FC++ Runtime for Position-Independent Flat Machine Code Generation\n**Turn Full-Fledged Modern C and C++20 Projects Directly into Standalone, In-Memory Runnable Flat Machine Code (`.bin`)**\n\n[![Continuous Integration](https:\u002F\u002Fgithub.com\u002FLaster-dev\u002FMemLLVM\u002Factions\u002Fworkflows\u002Fci.yml\u002Fbadge.svg)](https:\u002F\u002Fgithub.com\u002FLaster-dev\u002FMemLLVM\u002Factions\u002Fworkflows\u002Fci.yml)\n[![Build & Release](https:\u002F\u002Fgithub.com\u002FLaster-dev\u002FMemLLVM\u002Factions\u002Fworkflows\u002Frelease.yml\u002Fbadge.svg)](https:\u002F\u002Fgithub.com\u002FLaster-dev\u002FMemLLVM\u002Factions\u002Fworkflows\u002Frelease.yml)\n[![Platform](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FPlatform-Windows%20x64-0078D6.svg?logo=windows)](https:\u002F\u002Fmicrosoft.com)\n[![Toolchain](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FToolchain-LLVM%20%2F%20Clang--cl%2022-269539.svg?logo=llvm)](https:\u002F\u002Fllvm.org)\n[![Standard](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLanguage-C17%20%2F%20C%2B%2B20%20%2F%20C%2B%2B23-f34b7d.svg?logo=c%2B%2B)](https:\u002F\u002Fisocpp.org)\n[![Tests](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FTests-27%2F27%20Passed%20(100%25)-brightgreen.svg)](#-full-modern-c-regression-test-suite-27-tests)\n[![Coverage](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FC%2FC%2B%2B%20Coverage-%3E99.5%25-brightgreen.svg)](#-industrial-coverage--in-depth-architectural-boundaries)\n[![License](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLicense-MIT-blueviolet.svg)](LICENSE)\n\n[**English Documentation**](readme.md) | [**简体中文技术文档**](readme_zh.md)\n\n\u003C\u002Fdiv>\n\n---\n\n## 🌟 What is MemLLVM?\n\n**MemLLVM** is an industrial-grade compiler infrastructure built as an out-of-tree **LLVM New Pass Manager plugin** paired with a freestanding runtime library, specifically tailored for the Windows `clang-cl` toolchain.\n\nUnlike traditional shellcode generators, binary packers, or in-memory PE loaders (such as Reflective DLL Injection), **MemLLVM does not emulate Windows or wrap binaries in heavy multi-stage loaders**. Instead, it performs **deep LLVM Intermediate Representation (IR) transformations during compilation**, systematically stripping all assumptions about the operating system's native PE loader (`ntdll!LdrLoadDll`, section mapping and alignment, IAT resolution, relocation directories, and OS TLS slot allocation).\n\nThe result: Your high-level C or C++20 code (including templates, virtual inheritance, static constructors, multithreading, DirectX 11 graphics, and file I\u002FO) compiles into a **pure, contiguous, self-relocating flat binary image (`.bin`)**. It can be mapped into any executable memory page and executed directly via a single parameterless function pointer:\n\n```cpp\ntypedef void (*ShellcodeEntry)();\nShellcodeEntry entry = (ShellcodeEntry)pMemory;\nentry(); \u002F\u002F Boots up the C++20 runtime, static initializers, and enters main() instantly!\n```\n\n---\n\n## 🏗️ Architecture Pipeline\n\n```\n+-------------------------------------------------------------------------------------------------+\n|                                    MemLLVM Compilation Pipeline                                 |\n+-------------------------------------------------------------------------------------------------+\n|  [Modern C \u002F C++20 Source Code]  --->  [Clang AST Frontend \u002F LLVM IR Optimizer Engine]           |\n|                                                  |                                              |\n|                                                  v                                              |\n|                     +---------------------------------------------------------+                 |\n|                     |             MemLLVM 8-Stage IR Pass Plugin              |                 |\n|                     |  1. AutoMemoryPass     - Synthesizes Freestanding Heap  |                 |\n|                     |  2. StlStubPass        - Erases C++ Exception \u002F TLS     |                 |\n|                     |  3. GlobalLifecyclePass- Replaces .CRT$XCU with IR Ctor |                 |\n|                     |  4. GlobalSectionPass  - Merges .text\u002F.data\u002F.rdata\u002F.bss |                 |\n|                     |  5. GlobalPointerPass  - Dynamic VTable \u002F Pointer Delta |                 |\n|                     |  6. AutoLoadLibraryPass- Injects On-Demand Subsystem DLL|                 |\n|                     |  7. StackStringPass    - Function Compound Stack Pool JIT Decryption & Ephemeral Wipe     |\n|                     |  8. ApiResolvePass     - Strip IAT, Session-Polymorphic Parameterized PEB Hash Resolve    |\n|                     +---------------------------------------------------------+                 |\n|                                                  |                                              |\n|                                                  v                                              |\n|                         [Optimized COFF Object] + [LTL Runtime (ltl.lib)]                       |\n|                                                  |                                              |\n|                                                  v                                              |\n|                            [Flat Binary Extractor (extract_flat_bin.py)]                        |\n|                                  + [Self-Rebase Bootstrap Stub]                                 |\n|                                                  |                                              |\n|                                                  v                                              |\n|                ===================================================================              |\n|                >>> Pure Contiguous Self-Relocating Flat Binary Image (.bin) \u003C\u003C\u003C                |\n|                ===================================================================              |\n+-------------------------------------------------------------------------------------------------+\n```\n\n---\n\n## 🎯 Industrial Coverage & In-Depth Architectural Boundaries\n\nAcross numerous systemic refactorings and production iterations, MemLLVM has solved the core challenges of modern C++ in loaderless environments: virtual table rebasing, Windows resource directory parsing, ordinal-only imports, dual-CRT stdio conflicts, atomic initialization, freestanding memory management, and table-driven SEH exception unwinding.\n\n### ✅ Fully Supported at the Compiler & Runtime Layer (Conquered Capabilities):\n\n| Domain | Supported Capabilities & Engineering Principles |\n| :--- | :--- |\n| **Modern C++20\u002FC++23 Language Core** | Template metaprogramming, concepts, lambdas, `constexpr`, type traits, function pointers, multi-level virtual inheritance & dynamic polymorphism (`vtable`). **Meyers Thread-Safe Singletons Fully Supported**: `StlStubPass` rewrites implicit TLS checks and `_Init_thread_epoch` calls into atomic CAS instructions on flat memory, completely severing OS TLS dependencies. **C++20 Coroutines** (`co_await`, `co_return`, `std::coroutine_handle`) compiled down to 222 bytes flat binary. |\n| **Session-Polymorphic API Hash Randomization** | **Permanently eliminates fixed ROR13 static signature patterns**! Every build session derives or accepts an explicit `MEMLLVM_HASH_SEED` generating dynamic 4-parameter hashing (`Seed`, `ROT`, `MUL`, `XOR`); `Resolver.c` and `ApiResolvePass` dynamically inject parameters at compile time without any hardcoded hashes (including `LoadLibraryA`); `ltl.lib` decouples from user project seeds via `MemLLVM_GetApiAddressByName`, allowing a single static runtime archive to serve any user project. |\n| **Strings & Constants: Compound Stack Pool JIT Decryption & Ephemeral Wipe** | **Function Compound Stack Pool Architecture & Nanosecond Physical Zeroization**! `StackStringPass` merges all constants referenced by each function into an exclusive, compact read-only ciphertext pool (`@func.str_pool`) at compile time, and **completely erases the original plaintext global variables from the LLVM IR**; on function entry, allocates a single compound buffer on the stack and emits a single call to `__memllvm_jit_decrypt`. Constants within the function are indexed via single `lea` instructions with 0 byte instruction bloat; upon function exit (`ret`\u002F`resume`), emits a single `__memllvm_jit_wipe` call to physically zero the buffer. Binary size inflation across all targets is slashed from +84% down to **only +5.2%**, leaving 0 plaintext bytes in static binaries or persistent memory. |\n| **Native PE Resources (`.rsrc`) Fine-Grained Leaf Encryption** | **Per-Leaf Independent Random-Key Encryption & Ephemeral Erasure**! Extractor (`extract_flat_bin.py`) keeps the 3-level resource directory skeleton intact for $O(\\log N)$ traversal, while encrypting each leaf payload (bitmaps, icon bitstreams, dialog templates, menus, string tables) with unique random keys; LTL runtime (`crt_resources.cpp`) decrypts on demand, delegates to OS GDI\u002Fkernel objects (`CreateDIBitmap`, `CreateIconFromResourceEx`, `DialogBoxIndirectParamW`), and immediately executes `SecureZeroMemory` on ephemeral buffers before caching handles. |\n| **Native PE Resource Subsystem (`.rsrc`)** | **Full Win32 resource hierarchy without PE headers**! The extractor preserves the `.rsrc` physical section, while the bootstrap stub dynamically rebinds base addresses. The freestanding LTL runtime embeds an in-memory 3-level directory parser (Type -> Name\u002FID -> Language), transparently shimming `FindResource(Ex)A\u002FW`, `LoadResource`, `LockResource`, `SizeofResource`, `LoadStringA\u002FW` (decoding 16-entry Pascal strings), `DialogBoxParamA\u002FW`, `CreateDialogParamA\u002FW`, `LoadMenuA\u002FW`, `LoadAcceleratorsA\u002FW`, `LoadIconA\u002FW`, `LoadCursorA\u002FW`, `LoadBitmapA\u002FW`, and directory enumerators, with automatic fallback for system DLL resources. |\n| **Ordinal-Only (`[NONAME]`) Exports** | **Complete coverage of Windows un-named exports**! Pre-indexes all 2,729 ordinal exports across 80 system DLLs in Windows 10\u002F11 SDK with $O(\\log N)$ compile-time binary search; `ApiResolvePass` rewrites calls to `MemLLVM_GetApiAddressByOrdinal`; the bootstrap resolver natively handles recursive multi-hop forwarders (`DLL.#ordinal` and `DLL.func`) and `\u003Cdll>_Ordinal_\u003Cord>` calls. |\n| **C++ Exceptions & Stack Unwinding** | **Full `try` \u002F `catch` \u002F `throw` and rethrow (`throw;`) support**! Standalone table-driven SEH engine: the bootstrap stub dynamically registers `.pdata` function tables (`RtlAddFunctionTable`) with the Windows kernel using the `MEMLLVME` descriptor, guaranteeing 100% deterministic reverse-order execution of local RAII destructors during stack unwinding. |\n| **C++20 Synchronization & Concurrency** | Full synchronization suite: `std::thread`, `std::jthread`, `std::mutex`, `std::recursive_mutex`, `std::condition_variable`, `std::shared_mutex`, `std::async`, `std::future`, lock-free `std::atomic\u003CT>`. **C++20 Concurrency Primitives**: `\u003Csemaphore>` (`std::binary_semaphore`, `std::counting_semaphore`), `\u003Clatch>`, `\u003Cbarrier>`, and `std::atomic\u003CT>::wait\u002Fnotify` dynamically bound to `WaitOnAddress`\u002F`WakeByAddress*` in `kernelbase.dll` with SRWLOCK hash wait tables. |\n| **C++17 Parallel Algorithms** | `std::execution::par`, `std::execution::seq` (e.g., `std::sort(std::execution::par, v.begin(), v.end())`), seamlessly scheduled onto the Windows NT Threadpool (`PTP_WORK`) with aligned allocator support. |\n| **C++20\u002FC++23 Formatting & Print** | **On-Demand `std::format` Auto-Linking**: `StlStubPass` inspects translation unit symbols for `std::format` \u002F floating-point `std::to_chars` and automatically injects Ryu table dependencies (`ltl_format.lib`); strictly introduces **0 extra bytes** when unused. **C++23 `std::print` & `std::println`**: Native Unicode console bridge with UTF-8 to UTF-16 transcoding via `WriteConsoleW` and stream fallback. |\n| **C++23 Stacktrace & Diagnostics** | `\u003Cstacktrace>` (`std::stacktrace::current()`, `std::to_string(st)`, frame address formatting) without external debuggers or PDB dependencies; `\u003Csource_location>` (`std::source_location::current()`). |\n| **Time, Entropy & Localization** | C++20 `\u003Cchrono>` time zone database (`std::chrono::current_zone()`, `zoned_time`, `tzdb`) dynamically querying Win32 timezone info; `std::random_device` hardware entropy via `RtlGenRandom` (`SystemFunction036`) with `RDTSC` fallback; named locales `std::locale(\"zh-CN\")`, `std::locale(\"\")` with safe `_Locimp` heap lifetime management. |\n| **Dual-CRT Stdio & Console I\u002FO** | Directly disassembles and pierces the PEB, clearing the undocumented `WindowFlags` `0x400` and `0x200` intercept bits; simultaneously intercepts file descriptor tables in both `msvcrt.dll` and `ucrtbase.dll`, providing full support for `std::cout`, `std::cin`, `std::cerr`, `printf`, `wprintf`, `fgets`, pipe redirection, and interactive console REPLs. |\n| **Object Lifecycle Management** | Global and static constructors invoked automatically at startup (`@llvm.global_ctors`), registered destructors executed in reverse order on exit (`atexit`), precise RAII deterministic scoping. |\n| **Memory Allocation Subsystem** | Fully freestanding `malloc`, `free`, `realloc`, `calloc`, `operator new`, `operator delete`, aligned allocations, and high-performance bucketed arena allocators. |\n| **Graphics & System Ecosystem** | Native Win32 window message pumps, GDI vector rendering, **DirectX 11 \u002F DXGI hardware acceleration pipeline** (Dear ImGui), Windows multimedia audio (`winmm`), standard file streams (`std::fstream`), and filesystem paths (`std::filesystem`). |\n\n---\n\n### ⚠️ The 4 Real-World Architectural Boundaries & Best Practices:\n\nOperating completely outside the operating system's native PE loader inevitably meets fundamental system contracts and host process co-existence boundaries:\n\n#### 1. Module Identity & Filesystem Context Severance\n* **The `GetModuleHandle(NULL)` and `GetModuleFileName` Host Path**:\n  In loaderless execution, the operating system never assigns an independent `HMODULE` to the flat binary. Calling `GetModuleHandle(NULL)` or `GetModuleFileName(NULL, ...)` returns the **absolute path of the host process** (e.g., `explorer.exe` or the test loader).\n  - **Best Practice**: Never rely on `GetModuleFileName(NULL)` to locate companion assets. Pass paths explicitly via `main` arguments, use absolute paths, or embed assets as inline byte arrays.\n* **Current Working Directory (CWD) Reliance**:\n  Relative paths (e.g., `fopen(\"config.ini\", \"r\")`) resolve against the host process's active working directory.\n\n#### 2. Execution Morphology & Library Boundaries\n* **Single-Entry Payload Model vs. Shared Library (No EAT)**:\n  MemLLVM generates a standalone execution payload with a single entry point (offset 0 jumping to `main` after self-rebasing). **It cannot act as a multi-export Dynamic Link Library (DLL)** exporting dozens of named symbols for external callers.\n* **Strictly x64 Architecture Exclusivity**:\n  The entire pipeline (PE parsing, DIR64 fixups, ROR13 API resolution, 12-byte `.pdata` tables, and x64 assembly stubs) is hardcoded for the **Windows x86_64 ABI**. It does not support 32-bit x86 (IA-32) or ARM64.\n\n#### 3. Host Process Lifecycle Coupling\n* **The `exit()` \u002F `abort()` Host Termination Risk**:\n  In a standalone EXE, calling `exit(code)` terminates normally. When running as an in-memory payload inside a host process, calling `exit()` calls `ExitProcess`, **instantly killing the entire host process**!\n  - **Best Practice**: If the payload must return cleanly to the host, it must `return` from `main()` or invoke `ExitThread`. Avoid calling `exit()` in embedded scenarios.\n* **Direct Command Line (`GetCommandLine`) Query Pollution**:\n  `GetCommandLineA\u002FW` returns the host process's creation command line. While MemLLVM's stub reconstructs `main(argc, argv)`, libraries bypassing `main` and querying the PEB directly will observe host parameters.\n\n#### 4. Modern OS Security Mitigations\n* **W^X and DEP Memory Protection**:\n  Flat binaries require executable memory pages (allocated with `PAGE_EXECUTE_READWRITE` or switched from RW to RX via `VirtualProtect` before execution).\n* **Control Flow Guard (CFG) & Arbitrary Code Guard (ACG)**:\n  If the host process enforces strict Control Flow Guard (CFG), indirect calls into non-image dynamic memory trigger fast-fail `0xC0000409` unless registered via `SetProcessValidCallTargets`. If Arbitrary Code Guard (ACG) is enabled on the host, allocating executable memory dynamically is blocked by the Windows kernel.\n\n---\n\n## 🧪 Full Modern C++ Regression Test Suite (27\u002F27 Tests)\n\nMemLLVM maintains an exhaustive, continuously verified regression test suite located in [`tests\u002Frun_cpp_tests.bat`](tests\u002Frun_cpp_tests.bat). Every test undergoes the complete lifecycle: **Clang Compilation with MemLLVM Pass -> LLD Linking with LTL -> Flat Binary (.bin) Extraction -> In-Memory Execution via Python ctypes**:\n\n| Test ID | Validated Standard Library Feature | Test File | Flat Binary Validation |\n| :---: | :--- | :--- | :---: |\n| **01** | STL `std::vector` Dynamic Container | `test_cpp_stl_basic.cpp` | ✅ Status 0 (Returns 600) |\n| **02** | Global Objects & Dynamic Static Constructors | `test_cpp_global_obj.cpp` | ✅ Status 0 (Returns 1125) |\n| **03** | Virtual Inheritance, Polymorphism & VTables | `test_cpp_polymorphism.cpp` | ✅ Status 0 (Returns 275) |\n| **04** | Meyers Thread-Safe Local Statics (No TLS) | `test_cpp_thread_safe_static.cpp` | ✅ Status 0 (Returns 175) |\n| **05** | Complex Structs, Pointer Math & Constexpr | `test_cpp_struct_ptr_const.cpp` | ✅ Status 0 (Returns 777) |\n| **06** | Global Variables, `.data` & BSS Initialization | `test_cpp_globals_data_bss.cpp` | ✅ Status 0 (Returns 888) |\n| **07** | `std::mutex` Multi-Thread Lock Synchronization | `test_cpp_mutex.cpp` | ✅ Status 0 (Returns 350) |\n| **08** | `std::thread` Thread Creation & Joining | `test_cpp_thread.cpp` | ✅ Status 0 (Returns 400) |\n| **09** | Emulated Thread-Local Storage (`thread_local`) | `test_cpp_thread_local.cpp` | ✅ Status 0 (Returns 130) |\n| **10** | `std::filesystem` Directory & File Operations | `test_cpp_filesystem.cpp` | ✅ Status 0 (Returns 200) |\n| **11** | `std::cout` Stream Formatting & Redirection | `test_cpp_iostream.cpp` | ✅ Status 0 (Returns 105) |\n| **12** | `std::fstream` Disk File Reading & Writing | `test_cpp_fstream.cpp` | ✅ Status 0 (Returns 42) |\n| **13** | `std::cin` Interactive Console Stream Input | `test_cpp_cin.cpp` | ✅ Status 0 |\n| **14** | `std::regex` Regular Expression Matching | `test_cpp_regex.cpp` | ✅ Status 0 (Returns 88) |\n| **15** | `std::async` & `std::future` Promise\u002FFuture | `test_cpp_async.cpp` | ✅ Status 0 (Returns 100) |\n| **16** | C++20 Standard Modules (`import std;`) | `test_cpp_module_std.cpp` | ✅ Status 0 (Returns 77) |\n| **17** | Kernel Fast Direct Stdio (`kprintf`) | `test_stdio_kprintf.cpp` | ✅ Status 0 |\n| **18** | Multi-Translation-Unit Global Cross-Linking | `test_multi_tu_main.cpp` | ✅ Status 0 |\n| **19** | Command-Line Arguments Forwarding (`argc\u002Fargv`) | `test_argv_ansi.cpp` \u002F `_wide.cpp`| ✅ Status 0 |\n| **20** | Full C++ Exception Handling & RAII Unwind | `test_cpp_exceptions.cpp` | ✅ Status 0 |\n| **21** | Hardware Entropy (`std::random_device`) | `test_random.cpp` | ✅ Status 0 |\n| **22** | C++20 Chrono Timezone Database (`current_zone`)| `test_tz.cpp` | ✅ Status 0 |\n| **23** | C++17 Parallel Algorithms (`std::execution::par`)| `test_execution.cpp` | ✅ Status 0 |\n| **24** | C++20 `std::format` & Floating-Point Charconv | `test_format.cpp` | ✅ Status 0 |\n| **25** | C++20 `\u003Csemaphore>`, `\u003Clatch>`, `\u003Cbarrier>`, wait | `test_sync.cpp` | ✅ Status 0 |\n| **26** | C++23 Stacktrace (`std::stacktrace::current()`) | `test_stacktrace.cpp` | ✅ Status 0 |\n| **27** | Named Locales (`std::locale(\"zh-CN\")`) | `test_locale_named.cpp` | ✅ Status 0 |\n\n> 🚀 **Run the complete test suite locally**: Execute `tests\\run_cpp_tests.bat` to build, extract, and execute all 27 modern C++ flat binaries in ~30 seconds!\n\n---\n\n## 🕳️ Engineering Pitfalls & Battle-Tested Breakthroughs\n\nBuilding MemLLVM required navigating subtle, undocumented Windows kernel behaviors and compiler edge-cases. Here is a record of the hardest challenges solved during development:\n\n\u003Cdetails>\n\u003Csummary>\u003Cb>1. The Undocumented Windows \u003Ccode>GetStdHandle\u003C\u002Fcode> WindowFlags 0x400 \u002F 0x200 Trap\u003C\u002Fb> (Click to expand)\u003C\u002Fsummary>\n\n#### The Trap:\nWhen running CLI tools inside a GUI-based pipe loader, `SetStdHandle(STD_OUTPUT_HANDLE, hPipeWrite)` returned `TRUE`, yet subsequent calls to `GetStdHandle(STD_OUTPUT_HANDLE)` in the payload returned `0x(nil)` (NULL)! Native MSVC\u002FUCRT binaries saw NULL, assumed the process was non-interactive, and dropped all output or terminated instantly.\n\n#### The Discovery:\nWe disassembled Windows 11\u002F10 `kernelbase!GetStdHandle`:\n```x86asm\nGetStdHandle:\n    mov rax, gs:[0x60]                   ; rax = Current Process PEB\n    mov rcx, [rax + 0x20]                ; rcx = ProcessParameters\n    test dword ptr [rcx + 0xa4], 0x400   ; Test WindowFlags at offset 0xA4!\n    jne return_null                      ; If bit 0x400 is set, FORCIBLY RETURN NULL!\n    mov rax, [rcx + 0x28]                ; Otherwise return StandardOutput\n    ret\n```\nWhen a process is launched by Windows Explorer or `ShellExecuteEx`, Windows sets bit `0x400` in `WindowFlags`. Standard calls to `SetStdHandle` only write to the handle slot without clearing `0x400`! `GetStdHandle` sees the flag and forcibly returns NULL.\n\n#### The Breakthrough:\nMemLLVM's loader harness inspects the PEB directly via `__readgsqword(0x60)`, clears `0x400` (and stdin's `0x200`) from `ProcessParameters->WindowFlags`, and sets `STARTF_USESTDHANDLES (0x100)`, unlocking 100% reliable pipe and console I\u002FO for all native tools!\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cb>2. The Dual CRT File Descriptor Collision (\u003Ccode>msvcrt.dll\u003C\u002Fcode> vs \u003Ccode>ucrtbase.dll\u003C\u002Fcode>)\u003C\u002Fb> (Click to expand)\u003C\u002Fsummary>\n\n#### The Trap:\nRedirecting C runtime stdout via `_dup2(pipeFd, 1)` worked for tools linked with `msvcrt.dll`, but modern Windows payloads dynamically importing `ucrtbase.dll` wrote into a black hole—their `_write(1)` returned `-1` and `printf` output vanished.\n\n#### The Discovery:\n`msvcrt.dll` and `ucrtbase.dll` maintain completely separate, independent file descriptor tables inside the same process. Redirecting fd 1 in `msvcrt` has zero effect on `ucrtbase`!\n\n#### The Breakthrough:\nWe implemented dual-table redirection in the loader harness: dynamically inspecting and duplicating pipe handles across both `msvcrt` and `ucrtbase` via `DuplicateHandle`, ensuring every CRT flavor writes directly into the visual terminal.\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cb>3. The Clang Pass Plugin C++ ABI Mismatch (Heap Corruption \u003Ccode>0xC0000374\u003C\u002Fcode>)\u003C\u002Fb> (Click to expand)\u003C\u002Fsummary>\n\n#### The Trap:\nBuilding an out-of-tree LLVM pass plugin against LLVM header files and loading it into an official LLVM release installer crashed immediately during pass registration with `STATUS_HEAP_CORRUPTION (0xC0000374)`.\n\n#### The Discovery:\nLLVM's C++ codebase makes extensive use of STL containers (`std::vector`, `llvm::StringRef`, `llvm::SmallVector`) without an ABI freeze across builds. Minor compiler flag differences (e.g. `\u002FMT` vs `\u002FMD`, debug iterators, MSVC version differences) corrupt memory when passing objects across DLL boundaries.\n\n#### The Breakthrough:\nWe publish and commit a pinned, hermetic plugin-compatible compiler toolchain (`clang-plugin-toolchain.zip` in GitHub Releases and `release_artifacts\u002F`) ensuring 100% binary compatibility on every developer machine and GitHub CI runner.\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cb>4. Thread-Safe Local Statics (Meyers Singleton) Invoking Invalid TLS\u003C\u002Fb> (Click to expand)\u003C\u002Fsummary>\n\n#### The Trap:\nC++ guarantees thread-safe initialization of local static variables. MSVC and Clang implement this by emitting calls to `_Init_thread_epoch` and accessing `__tls_index` via `gs:[0x58]`. In a flat binary, this immediately triggered an access violation (`0xC0000005`).\n\n#### The Breakthrough:\nMemLLVM's `StlStubPass` detects these compiler-generated TLS checks at the IR level and rewrites them into atomic lock-free compare-and-swap operations on non-TLS global storage, completely eliminating the OS TLS dependency while preserving thread safety!\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cb>5. Windows x64 SEH Exception Unwinding & The Missing \u003Ccode>.pdata\u003C\u002Fcode> Pitfall\u003C\u002Fb> (Click to expand)\u003C\u002Fsummary>\n\n#### The Trap:\nAfter implementing `_CxxThrowException`, `__CxxFrameHandler3`, and registering function tables via `RtlAddFunctionTable`, throwing an exception (`throw 42;`) still caused the process to abruptly crash with unhandled exception code `0xE06D7363`, completely bypassing the outer `catch` handler.\n\n#### The Discovery:\nWindows x64 employs a strictly table-driven exception dispatch model. When `_CxxThrowException` calls `ntdll!RaiseException`, the kernel SEH dispatcher invokes `RtlVirtualUnwind` to walk backward through the call stack. If any non-leaf function frame (including `_CxxThrowException` itself!) lacks `.pdata` unwind metadata (e.g. because `\u002Fclang:-fno-unwind-tables` was enabled during CRT compilation), the kernel's `RtlLookupFunctionEntry` query returns `NULL`. Unable to compute the previous `RSP`, **the kernel immediately aborts the unwind search and terminates the process**!\n\n#### The Breakthrough:\n1. Compiled `ltl\u002Fsrc\u002Fcrt_exceptions.cpp` specifically with `\u002FEHsc` to preserve full `.pdata` and `.xdata` unwind tables.\n2. Updated `extract_flat_bin.py` to preserve and extract the `.pdata` section into the flat image.\n3. In the bootstrap self-rebase stub, dynamically bound the `MEMLLVME` descriptor with the runtime image base, `.pdata` pointer, and count. This seamlessly drives `RtlAddFunctionTable` and `RtlDeleteFunctionTable` for zero-overhead, flawless C++ exception handling (`try`\u002F`catch`\u002F`throw`\u002Frethrow) and RAII stack unwinding in flat shellcode!\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cb>6. Undocumented Ordinal-Only (\u003Ccode>[NONAME]\u003C\u002Fcode>) Exports & Multi-Hop Forwarder Chains\u003C\u002Fb> (Click to expand)\u003C\u002Fsummary>\n\n#### The Trap:\nCalling common Windows Shell or networking APIs (such as `SHAlloc`, `SHFree`, or `ConnectToConnectionPoint`) works normally in a standard executable, but when converted into flat shellcode, calls crash immediately with a null pointer (`0x00000000`) or linger as unresolved link-time imports.\n\n#### The Discovery:\nThe PE specification allows DLLs to export functions purely by numeric index (`[NONAME]`), omitting function name strings from `AddressOfNames`. `shlwapi.dll` alone contains 551 ordinal-only exports, and `shell32.dll` contains 364. Standard ROR13 export table scanners return NULL. Furthermore, many ordinals are forwarded to other libraries (e.g. `SHUNIMPL.#429` or `NTDLL.RtlAllocateHeap`); naively jumping to the exported RVA executes ASCII forwarder string data instead of machine code!\n\n#### The Breakthrough:\n1. Implemented an $O(1)$ runtime ordinal indexer (`funcs[ordinal - Base]`) in the bootstrap resolver with multi-hop forwarder resolution supporting both string and `#ordinal` forwarded targets with cycle detection;\n2. Pre-indexed all 2,729 Windows SDK ordinal exports across 80 system DLLs into a compile-time binary search table and added dynamic `.lib` archive header scanning for project-local dependencies;\n3. Connected `AutoLoadLibraryPass`, `ApiResolvePass`, and `GlobalPointerPass` to transparently rewrite calls and rebase vtable\u002Fglobal pointer slots to `MemLLVM_GetApiAddressByOrdinal`.\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cb>7. Reconstructing Native PE Resource Subsystem (\u003Ccode>.rsrc\u003C\u002Fcode>) in Headless Flat Binaries\u003C\u002Fb> (Click to expand)\u003C\u002Fsummary>\n\n#### The Trap:\nWindows developers extensively use `.rc` resource scripts to bundle icons, string tables (`STRINGTABLE`), dialog templates (`DIALOGEX`), menus, accelerators, and raw binary assets (`RCDATA`). In flat binaries without PE headers, calling `FindResource`, `LoadString`, or `DialogBoxParam` fails with NULL or triggers crashes.\n\n#### The Discovery:\nWin32 resource functions under `kernel32` \u002F `user32` traverse the PE resource tree by interpreting `hModule` as the base address of a valid PE image and scanning DOS\u002FNT headers. Flat binaries have no PE headers, so passing `GetModuleHandle(NULL)` reads the host process's resources, while passing the payload's own address returns `ERROR_RESOURCE_DATA_NOT_FOUND (1812)`. Furthermore, Clang generates `__imp_*` slot loads that normally resolve to `kernel32.lib` \u002F `user32.lib`, re-introducing dangerous import dependencies into the flat binary.\n\n#### The Breakthrough:\n1. **Preserving and Packing `.rsrc`**: `extract_flat_bin.py` preserves the `.rsrc` section in the flat image and injects a `MemLLVM_ResourceInfo` descriptor that dynamically binds the resource base address and RVA offset at runtime startup.\n2. **In-Memory 3-Level Resource Traversal Engine**: Implemented an in-memory `IMAGE_RESOURCE_DIRECTORY` parser in `ltl\u002Fsrc\u002Fcrt_resources.cpp` supporting both integer IDs (`MAKEINTRESOURCE`) and Unicode name strings across all three directory levels (Type -> Name\u002FID -> Language).\n3. **Comprehensive Win32 Resource API Shims**:\n   - Navigation & Access: `FindResource(Ex)A\u002FW`, `LoadResource`, `LockResource`, `SizeofResource`.\n   - String Tables: `LoadStringA\u002FW` (parsing 16-entry Pascal counted string blocks).\n   - Dialogs & Menus: `DialogBoxParamA\u002FW` & `CreateDialogParamA\u002FW` (via indirect dialog templates), `LoadMenuA\u002FW`, `LoadAcceleratorsA\u002FW`.\n   - Graphics & Icons: `LoadIconA\u002FW`, `LoadCursorA\u002FW`, `LoadBitmapA\u002FW`.\n   - Enumeration: `EnumResourceTypesW`, `EnumResourceNamesW`, `EnumResourceLanguagesW`.\n   - Fallback: Transparently delegates to OS APIs when `hModule` points to external system DLLs (e.g. `IDI_APPLICATION`, `IDC_ARROW` in `user32.dll`).\n4. **Compile-Time Import Interception**: `ApiResolvePass` marks all 26 resource APIs as static shims, rewriting `__imp_*` loads directly to `ltl.lib` functions in IR, completely eliminating OS import stubs.\n\u003C\u002Fdetails>\n\n---\n\n## 🏆 Verified Showcase Projects (From `examples\u002F`)\n\nEvery project in `examples\u002F` compiles directly from source into a **standalone, self-relocating flat binary (`.bin`)** and is continuously compiled and verified on GitHub Actions CI:\n\n```\nexamples\u002F\n├── box2d\u002F       # Box2D 3.0 2D Physics Engine (45 files, real-time GDI rendering)\n├── chip8\u002F       # Full CHIP-8 CPU \u002F Sound Virtual Machine (C++20, plays Pong\u002FTetris)\n├── doom\u002F        # Classic DOOM 3D Game Engine (83 files, software rasterizer, audio)\n├── imgui\u002F       # Dear ImGui v1.91+ (Hardware-accelerated DirectX 11, multi-windows)\n├── sqlite\u002F      # Official SQLite3 CLI Shell (Full interactive REPL, SQL engine)\n├── winmine\u002F     # Classic Win32 Minesweeper (Full PE resource tree, DialogBoxParam, LoadMenu, Bitmaps)\n├── mimikatz\u002F    # Large-scale Complex C Project (114 TUs, tentative definitions, subsystems)\n└── mock_cli\u002F    # Interactive CLI Diagnostic Stub (Testing stdio pipes & arguments)\n```\n\n| Showcase Project | Scale & Language | Flat Binary Size | Key Validated Capabilities |\n| :--- | :--- | :--- | :--- |\n| **[Classic Win32 Minesweeper](examples\u002Fwinmine\u002F)** | Pure C \u002F Win32 (ReactOS Port) | **1.01 MB** | **Ultimate Native Resource Subsystem Showcase**: Bundles `.rsrc` directly into flat memory. Seamlessly parses `DialogBoxParamW` (Custom Game & Fastest Times modal dialogs), `LoadMenuW` menus, `LoadBitmapW` (smiley face, LED numbers, mine tiles), `LoadIconW`, `LoadAcceleratorsW`, and `LoadStringW` directly from memory without PE headers. |\n| **[Official SQLite3 CLI](examples\u002Fsqlite\u002F)** | C \u002F SQLite 3.45 | **208 KB** | Full interactive SQL REPL, in-memory database creation, complex SQL queries, table formatting, pipe streaming. |\n| **[Classic DOOM Engine](examples\u002Fdoom\u002F)** | Pure C (83 files) | **605 KB** | Full id Software DOOM engine, 3D software rasterization, keyboard controls, audio mixer, streaming IWAD data. |\n| **[Dear ImGui v1.91+](examples\u002Fimgui\u002F)** | C++17 Industrial UI | **813 KB** | Full immediate-mode GUI, multi-window docking, plots, widgets, hardware-accelerated **DirectX 11 \u002F DXGI** pipeline. |\n| **[Box2D 3.0 Engine](examples\u002Fbox2d\u002F)** | Pure C (45 files) | **545 KB** | Continuous rigid body physics, dynamic BVH trees, collision impulse solver, real-time Win32 GDI vector rendering. |\n| **[CHIP-8 Virtual Machine](examples\u002Fchip8\u002F)** | Modern C++20 | **30 KB** | 35-opcode CPU emulation, frame timers, audio buzzer, 64x32 monochrome display matrix running *Pong* and *Tetris*. |\n| **[Mimikatz 2.2.0](examples\u002Fmimikatz\u002F)** | Complex C (114 Translation Units) | **1.20 MB** | Massive real-world code base testing tentative definitions merging, dynamic subsystem resolution, multi-tier struct alignment, and dual-CRT stdio pipe redirection. |\n| **[Mock CLI Diagnostic Stub](examples\u002Fmock_cli\u002F)** | Minimal C Runtime | **4.6 KB** | Dedicated diagnostic tool testing full-duplex stdio pipes, command line argument forwarding, streaming output throughput, and graceful exit handling. |\n\n> 💡 **Batch Compile All Examples Locally**: Run `python examples\u002Fbuild_all.py` from the repository root to compile and extract all 7 showcase binaries in ~15 seconds!\n\n---\n\n## 🚀 Quick Start Guide\n\n### Path A: CLI Fast Track (Recommended)\n\nNo complex IDE required. Convert any C\u002FC++ project into a standalone flat binary in 4 clean steps:\n\n```bat\n:: 1. Compile source into COFF object with the MemLLVM IR Pass plugin\nclang-cl \u002Fc \u002FO2 \u002FGS- \u002FGR- \u002Fclang:-fpass-plugin=\"%MEMLLVM_DIR%\\bin\\MemLLVM.dll\" ^\n  \u002Fclang:-fno-jump-tables \u002Fclang:-fno-builtin ^\n  \u002FI\"%MEMLLVM_DIR%\\include\" \u002FI\"%MEMLLVM_DIR%\\ltl\\include\" ^\n  main.cpp \u002FFo:main.obj\n\n:: 2. Link with the freestanding LTL runtime (no default CRT libraries)\nlld-link \u002FNODEFAULTLIB \u002FENTRY:main \u002FOPT:REF \u002FOPT:ICF \u002FALIGN:512 \u002FMERGE:.rdata=.text ^\n  \u002FLIBPATH:\"%MEMLLVM_DIR%\\lib\" \u002FLIBPATH:\"%MEMLLVM_DIR%\\ltl\" ^\n  main.obj ltl.lib kernel32.lib user32.lib \u002FOUT:main.exe\n\n:: 3. Extract the position-independent flat binary (.bin)\npython \"%MEMLLVM_DIR%\\Tools\\extract_flat_bin.py\" main.exe main.bin\n\n:: 4. Execute and inspect immediately with the bundled loader\n\"%MEMLLVM_DIR%\\Tools\\scloader_cli.exe\" main.bin\n```\n\n---\n\n### Path B: Visual Studio Project (.vcxproj) Configuration\n\n#### 1. Download & One-Click Environment Setup\n1. Download `MemLLVM-SDK-windows-x64.zip` from the latest [GitHub Releases](https:\u002F\u002Fgithub.com\u002FLaster-dev\u002FMemLLVM\u002Freleases).\n2. Extract to any directory (e.g. `C:\\MemLLVM`).\n3. **Double-click `setup_env.bat`**:\n   - Automatically sets `MEMLLVM_DIR` in your User Environment.\n   - **Auto-Binds Bundled Hermetic Toolchain**: Sets `LLVMInstallDir` to the SDK's embedded `toolchain\u002F` directory so Visual Studio ClangCL automatically invokes the exact binary-aligned `clang-cl.exe`, eliminating host Clang ABI mismatches and plugin loading errors!\n   - Mounts `toolchain\\bin`, `bin`, and `Tools` into your User `PATH`.\n   - **Smart Path Migration**: Moving the SDK in the future? Just run `setup_env.bat` again in the new folder—it automatically purges old stale paths.\n   - **One-Click In-Place Auto-Update**: The SDK comes with `update.bat`. Run it at any time to automatically fetch the latest release from GitHub and overwrite your local SDK in-place, then re-synchronize configurations.\n\n#### 2. Enable Clang in Visual Studio\n* **Option A (Recommended Built-in Component)**: Open Visual Studio Installer -> Modify -> Individual components -> Search `Clang` -> Check **C++ Clang Compiler for Windows** and **MSBuild support for LLVM toolset**.\n* **Option B (VSIX Extension)**: Visual Studio Extensions -> Manage Extensions -> Search & Install **LLVM Compiler Toolchain**.\n\n#### 3. Visual Studio Project (.vcxproj) Properties\nIn your project properties:\n1. **General** -> **Platform Toolset**: Select **LLVM (clang-cl)**.\n2. **C\u002FC++** -> **General** -> **Additional Include Directories**:\n   ```text\n   $(MEMLLVM_DIR)\\include;$(MEMLLVM_DIR)\\ltl\\include;%(AdditionalIncludeDirectories)\n   ```\n3. **C\u002FC++** -> **Code Generation**:\n   - Runtime Library: **Multi-threaded (\u002FMT)**\n   - Enable C++ Exceptions: **Yes (`\u002FEHsc`)** (Fully supports exception handling & RAII stack unwinding; or **No (`\u002FEHs-c- \u002FGR-`)** if minimal binary size is desired)\n   - Security Check: **Disable Security Check (`\u002FGS-`)**\n4. **C\u002FC++** -> **Command Line** -> **Additional Options**:\n   ```text\n   \u002Fclang:-fpass-plugin=\"$(MEMLLVM_DIR)\\bin\\MemLLVM.dll\" \u002Fclang:-fno-jump-tables \u002Fclang:-fno-builtin\n   ```\n5. **Linker** -> **General** -> **Additional Library Directories**:\n   ```text\n   $(MEMLLVM_DIR)\\lib;$(MEMLLVM_DIR)\\ltl;%(AdditionalLibraryDirectories)\n   ```\n6. **Linker** -> **Input**:\n   - Ignore All Default Libraries: **Yes (`\u002FNODEFAULTLIB`)**\n   - Additional Dependencies: `ltl.lib;kernel32.lib;user32.lib;gdi32.lib;d3d11.lib;`\n7. **Linker** -> **Advanced**:\n   - Entry Point: **`main`**\n8. **Build Events** -> **Post-Build Event**:\n   ```bat\n   python \"$(MEMLLVM_DIR)\\Tools\\extract_flat_bin.py\" \"$(TargetPath)\" \"$(TargetDir)$(TargetName).bin\"\n   ```\n\n---\n\n## 🖥️ SCLoader \u002F CSLoader: Open-Source Status & Standalone Tool\n\nIn the `Tools\u002F` directory, MemLLVM provides **SCLoader** (`Tools\u002FSCLoader.exe`), a modern GUI runner and interactive payload debugger built specifically for executing, inspecting, and testing flat machine code images.\n\n> **Notice on CSLoader Source Code**:  \n> SCLoader's visual presentation is powered by **CUI (Contemporary UI)**, an extensive proprietary Direct2D \u002F DirectWrite Fluent Design GUI framework. Because the underlying CUI framework is a commercial enterprise component not yet cleared for open-source release, **we cannot open-source the full GUI library repository at this time**.  \n> \n> However, to ensure full transparency and community utility:\n> 1. We provide the **complete core execution harness source code** in [`CSLoader\u002F`](CSLoader\u002F) (including the x64 assembly execution bridge `CallShellcode.asm`, SEH exception harness, privilege elevation\u002Fde-elevation dispatcher, and pipe redirection engine).\n> 2. We provide the **fully compiled standalone tool `Tools\u002FSCLoader.exe`** in every release, completely free for all users to test, run, and debug flat binaries!\n\n---\n\n## 💖 Acknowledgements & Credits\n\nMemLLVM stands on the shoulders of giants. We express our deepest gratitude to:\n\n* **[VC-LTL](https:\u002F\u002Fgithub.com\u002FChuyu-Team\u002FVC-LTL5)** and the Chuyu-Team: For setting the gold standard in lightweight Windows CRT engineering and dependency-free runtime architecture. MemLLVM's freestanding LTL philosophy was deeply inspired by VC-LTL.\n* **[The LLVM Project](https:\u002F\u002Fllvm.org)**: For creating the most modular, powerful compiler intermediate representation and New Pass Manager ecosystem.\n* **[Omar Cornut](https:\u002F\u002Fgithub.com\u002Focornut)** & The Dear ImGui Community: For the legendary immediate-mode GUI framework.\n* **[Erin Catto](https:\u002F\u002Fgithub.com\u002Ferincatto)** & The Box2D Project: For the industry-standard 2D rigid body physics engine.\n* **id Software & John Carmack**: For the immortal, beautifully written classic DOOM engine.\n* **D. Richard Hipp & The SQLite Team**: For the most reliable, elegant, and versatile database engine in history.\n\n---\n\n## 📈 Star History\n\n[![Star History Chart](https:\u002F\u002Fapi.star-history.com\u002Fsvg?repos=Laster-dev\u002FMemLLVM&type=Date)](https:\u002F\u002Fstar-history.com\u002F#Laster-dev\u002FMemLLVM&Date)\n\n---\n\n## 📄 License\n\nThis project is licensed under the [MIT License](LICENSE).\nAll example projects and third-party libraries retain their respective original licenses.\n","MemLLVM 是一个基于 LLVM 的无限制 Shellcode 编译器，可将标准 C17\u002FC++20 代码直接编译为位置无关、自重定位的扁平化机器码二进制（.bin）。其核心通过自研 LLVM 新 Pass 管理器插件，在 IR 层深度剥离 PE 加载依赖（如 IAT、重定位表、TLS、节对齐等），配合轻量级 freestanding 运行时，生成无需 OS 加载器即可在任意可执行内存页中直接调用的纯函数入口。适用于红队工具开发、内存驻留 payload 构建、EDR 绕过研究及底层安全实验等需高度可控、零依赖原生执行的场景。","2026-11-24 04:40:55","CREATED_QUERY"]