Skip to main content

MBPRBF

MBPRBF (Madmen Builder for Programs on Raw Bytes Framework) — фреймворк для описания логики Windows-приложения на Python и получения нативного PE-файла (.exe) под Windows x64, без компилятора C/C++ и без рантайм-зависимостей.

Сборщик сам генерирует машинный код x86-64, собирает секции PE (.text, .rdata, .data, .rsrc, .pdata, .xdata, .reloc), таблицы импорта, ресурсы (иконки, манифест, версия), SEH-таблицы и корректный PE-заголовок.

License: GPL v3 Python 3.12+ Platform: Windows x64 PyPI

Python-описание (GUI / Console / GDI)  ───►  Нативный .exe (x64)
                                             без Python, без DLL-рантайма

Содержание

License

MBPRBF is licensed under the GNU General Public License v3.0 or later (GPL-3.0-or-later). See LICENSE for the full text.

Copyright (C) 2026 Madmen3733.

Author

Madmen3733 — github.com/madmenmadmen

Возможности

  • Три типа приложений:
    • консольные (IMAGE_SUBSYSTEM_WINDOWS_CUI),
    • GUI (IMAGE_SUBSYSTEM_WINDOWS_GUI),
    • GDI (рисование поверх окна).
  • Прямая эмиссия машинного кода x86-64.
  • Система методов по Microsoft x64 ABI: RCX/RDX/R8/R9 + XMM0–XMM3, счётчики int/float, forward references для рекурсии, корректное выравнивание RSP, varargs.
  • Массивы MBPRBF — смешанные/однородные, статические/динамические.
  • Структуры WinAPI на ctypes с релокацией RVA-полей.
  • FFI — экспорт C-функций из DLL с автопроверкой экспортов.
  • SEH x64 — try_ / except_ / finally_, .pdata / .xdata.
  • Трекер памяти на этапе сборки.
  • Ресурсы PE — иконки, манифест, VS_VERSIONINFO.
  • GDI-изображения — PNG → DIB → CreateDIBSection, спрайты с маской.

Архитектура

Пользовательский код (build_console / build_gui / build_gdi)
        │
        ├── console_builder.py
        ├── gui_builder.py
        └── gdi_builder.py
                │
                ▼
        Контексты (contexts.py)
        Context → GUIContext / ConsoleContext / GDIContext
                │
        ┌───────┼───────────┐
        ▼       ▼           ▼
   asm_helper  methods    seh
                │
                ▼
        PE-сборщик (pe_builder.py)

Быстрый старт

Фасады gui.py / gdi.py реэкспортируют Window, Button, add_string, build_gui / build_gdi через from ... import *, поэтому тянуть их напрямую из widgets.py, data.py, gui_builder.py не обязательно.

Консоль

from console_builder import build_console
from data import add_string

add_string("_hello", "Hello, MBPRBF!\r\n")

def main(ctx):
    ctx.write_str("_hello")

build_console("hello.exe", main)

Альтернатива — add_string реэкспортируется самим console_builder.py:

from console_builder import build_console, add_string

GUI

from gui import (
    Window, Button,
    build_gui, add_string,
)

add_string("_title", "Demo")
add_string("_msg", "Clicked!")

def on_click(ctx):
    ctx.message_box_str("_msg", "_title", 0)

win = Window("Demo", 400, 300)

btn = Button(
    name="btn1",
    text="Click me",
    id_val=1001,
    x=20, y=20, w=120, h=32,
    on_click=on_click,
    parent=win,
)

build_gui("demo.exe", [win], [btn], timers=[])

GDI

from gdi import (
    Window, Rect, Circle, Text,
    build_gdi, add_string, rgb,
)

add_string("_title", "GDI Demo")

win = Window("GDI Demo", 640, 480, double_buffer=True)

shapes = [
    Rect(20, 20, 200, 100, fill=rgb(200, 30, 30), border=0),
    Circle(320, 240, 80, fill=rgb(30, 120, 200), border=0),
    Text(20, 400, "Hello, GDI", color=0x000000, size=24),
]

build_gdi("gdi_demo.exe", [win], [], shapes, timers=[])

Массивы

Слот Array в .data — 96 байт:

Смещение Размер Поле Описание
+0x00 8 ptr указатель на данные (heap)
+0x08 8 length количество элементов
+0x10 8 capacity ёмкость данных, байт
+0x18 8 used_bytes занято байт (после выравнивания)
+0x20 8 types_ptr uint32[] коды типов
+0x28 8 offsets_ptr uint32[] смещения
+0x30 8 offsets_capacity ёмкость types/offsets
+0x38 4 elem_size размер для однородных
+0x3C 4 flags битовые флаги

Создание — arrays.array(...). Runtime-операции — методы ctx (они сами вызовут ensure_runtime с нужным набором зависимостей):

import ctypes
from arrays import array, array_get, array_set, array_len, array_free

a = array([1, 2, 3])                       # динамический int32
b = array([1.5, 2.5], types=[ctypes.c_float])
c = array(size=10)                          # статический, int32
d = array(size=10, type=ctypes.c_float)     # статический, float32

# read/write — статика/динамика
array_get(ctx, a, 1)                        # или ctx.array_get(a, 1)
array_set(ctx, a, 1, 42)
array_len(ctx, a)

# runtime-операции — только для динамических
ctx.array_append(a, 4)
ctx.array_insert(a, 1, 99)
ctx.array_remove(a, 0)
ctx.array_resize(a, 8)

array_free(ctx, a)

Методы и WinAPI

import ctypes

ctx.start_method("add", [ctypes.c_int32, ctypes.c_int32],
                 ret_type=ctypes.c_int32)
# ... эмиссия тела ...
ctx.end_method()

ctx.call_method("add", (5, 7))
ctx.call_iat("MessageBoxA")

FFI и структуры

ffi_export_method возвращает Method и регистрирует его под именем "_" + alias (или "_" + name, если alias не задан). Именно это имя нужно передавать в call_method.

import ctypes

ctx.ffi_export_method(
    "GetTickCount", "kernel32.dll",
    args=[], ret=ctypes.c_uint32, alias="GetTickCount",
)
ctx.call_method("_GetTickCount", [])

Структуры:

from data import data_alloc_struct
data_alloc_struct("_ofn", "OPENFILENAMEA")

SEH

with ctx.try_():
    # ...
    with ctx.except_(EXCEPTION_EXECUTE_HANDLER):
        pass

with ctx.try_():
    pass
    with ctx.finally_(lambda c: c.call_iat("CloseHandle")):
        pass

Трекер памяти

memory_tracker.py ловит на этапе сборки:

  • двойную аллокацию,
  • double free,
  • use-after-free,
  • утечки (check_all_freed()).

Модули

Файл Назначение
asm_helper.py эмиттеры инструкций, call_iat, call_rva, ветвления
methods.py ABI, прологи/эпилоги, start_method / call_method
contexts.py Context, GUIContext, ConsoleContext, GDIContext
console_builder.py сборка .exe для CUI
gui_builder.py сборка .exe для GUI + .rsrc
gdi_builder.py надстройка над GUI для GDI
widgets.py виджеты, Window, Timer
gdi_objects.py фигуры, rgb, вращение
structs.py WinAPI-структуры
data.py .data: DATA_ALLOC, строки, структуры
mb_array.py ядро массивов
arrays.py регистрация, init, get/set/len/free
array_runtime.py append / insert / remove / resize
array_validator.py валидация и трекинг
memory_tracker.py трекер аллокаций
seh.py .pdata / .xdata, UnwindInfo, scope-таблицы
runtime_guard.py SEH-guard и __C_specific_handler wrapper
pe_builder.py PE-заголовок, секции, .rsrc, .reloc
imports.py IMPORT_DLL, CORE_IMPORTS, CONSOLE_CORE_IMPORTS
consts.py WinAPI-константы

Ограничения

  • Только Windows x64, MS ABI.
  • Нет встроенного аллокатора регистров — промежуточные значения живут на стеке.
  • Стек методов фиксируется на этапе end_method.
  • Плавающая точка — только через XMM или x87-эмиттеры, без выражений.

Metadata

Release files for mbprbf 1.0.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mbprbf 1.0.5
File Size Uploaded Provenance Actions
mbprbf-1.0.5.tar.gz 101.3 kB Without provenance Details for mbprbf-1.0.5.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for mbprbf 1.0.5
File Interpreter ABI Platform Actions
mbprbf-1.0.5-py3-none-any.whl Python 3 none any Details for mbprbf-1.0.5-py3-none-any.whl

Total release size: 214.8 kB

Release files / mbprbf-1.0.5.tar.gz

Download URL mbprbf-1.0.5.tar.gz
Size 101.3 kB
Tags Source
SHA-256 checksum
How to use checksums
1ae6e344de85ffa31bbb1c4cbae1a93518cb7595b94f213d8dba244f7ae90509
BLAKE2b-256 checksum
How to use checksums
80e142cd2d2fbef6588e382f31eb8f335dca2b15ce8348156af40fd54e1e92ac
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.9

Release files / mbprbf-1.0.5-py3-none-any.whl

Download URL mbprbf-1.0.5-py3-none-any.whl
Size 113.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c7f759888d28ee75e49978c91831e380de72c262d6677a364a85fa6517e1b361
BLAKE2b-256 checksum
How to use checksums
8244f58dd10cde951b9f766cbe2fd9732112033ae334a618f345f649e8781208
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.9

Security for mbprbf 1.0.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page