BitKindle README

README проекта с github.com/tombkeeper/BitKindle. Одним файлом markdown: README.md.

简体中文 · English

BitKindle

A Windows x64 C compiler bootstrapped from a 3,584-byte machine-code seed

Platform: Windows x64 Seed: 3584 bytes Bootstrap: self-hosted License: MIT

Quick start · Bootstrap design · Walkthrough · Usage · Examples

Mario built with BitKindle

Mario example built with the BitKindle toolchain
Actual gameplay recording · Built-in automated player completes the level · Preview at 2× speed
Build and run instructions


Overview

BitKindle includes the complete sources for the A0/A1 assemblers, C0 transitional compiler, self-hosted C1 compiler written in C, runtime library, and PE linker.

Building requires no MSVC, GCC, Clang, Windows SDK, or external linker, and downloads no dependencies. PowerShell 5.1 decodes the seed and orchestrates the build. After decoding, every machine-code binary, object file, and EXE is generated by previously built custom tools.

Bootstrap pipeline

flowchart LR
    S["Hexadecimal seed<br/>3,584 bytes"] --> A["A0 → A1<br/>Custom assemblers"]
    A --> C["C0 → Bridge stages<br/>Transitional compilers"]
    C --> O["Progressive C1 extensions<br/>Object-file support"]
    O --> L["Custom PE linker"]
    O --> H["Final C1 + runtime"]
    L --> H
    H --> G1["Self-compiled generation 1"]
    G1 --> G2["Self-compiled generation 2"]
    G1 -. "Byte-identical" .-> G2

See BOOTSTRAP.md for stage dependencies and WALKTHROUGH.md for building individual stages with build-stage.ps1.

Quick start

Requires Windows x64 and Windows PowerShell 5.1 (powershell.exe); the verified environment is Windows 10 x64. Place the complete source tree in a writable local directory with a short path, preserving the name and hierarchy of src/. Reserve 5 GiB for the full test run.

Run from the release root:

powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File .\build-all.ps1

The default builds the compiler, linker, and C89/C99 runtimes, without running regression tests. After a successful build, compile and run hello:

$snapshot = './src/bootstrap-c99'
& "$snapshot/compile-program.ps1" -Source "$snapshot/examples/hello.c" `
    -Output './work/my-hello.exe' -BuildDirectory "$snapshot/build-from-seed" -Standard c89
if (!$?) { throw 'Compilation failed' }
& './work/my-hello.exe'

Expected output: hello.

Build modes

Append a mode option to the build command. All three modes build from the seed and check self-compilation identity and the compiler baseline. -All and -Full are mutually exclusive.

Option Build and test scope
None Toolchain and runtimes; no regression tests
-All Default mode plus compilation of hello, the argument example, minicurl, and Mario; does not run examples or regression tests
-Full Stage regressions, full audit, three supplemental suites, hello and argument examples, and minicurl local HTTP tests; Mario has separate build and test entry points

Logs and results are in work/release-run/. For default and -All, RESULT.json reports Status=BUILT and TestsRun=false. A successful -Full reports Status=PASS, TestsRun=true, and prints PASS release build and verification. An output directory alone is not evidence of success.

build-all.ps1 refuses to run if src/bootstrap-c99/build-from-seed/ or work/release-run/ already exists. Before rebuilding or changing modes, clean the default outputs or use a fresh source copy.

Examples

Example Features and interfaces Documentation
Hello / command-line arguments C runtime, startup, argc/argv Compilation and usage
minicurl HTTP/TLS through system WinHTTP; retrieve content and save it to a file Source and usage
Mario first level Side scrolling, keyboard input, collisions, timers, and GDI double buffering; graphics drawn in C Build and controls

With an existing toolchain, build examples individually using their documentation. Run them manually after building:

# GUI platform game
& './src/examples/mario/build/mario.exe'

# Optional online demo; requires working Windows networking and certificates
& './src/examples/minicurl/minicurl.exe' -o './work/example.html' 'https://example.com/'

Mario is an educational gameplay recreation; its documentation describes differences from the original.

Build artifacts and interfaces

The primary tools are:

src/bootstrap-c99/build-from-seed/
├── host/c1-stage2.exe    # C compiler
└── link-stage2.exe      # Custom Windows x64 PE linker

C1 reads C source from standard input and writes PE or .c1o object bytes to standard output. For ordinary programs, compile-program.ps1 configures headers, the runtime, and linker arguments.

See USAGE.md for multiple source files, command-line arguments, Windows DLL imports, and GUI subsystem selection.

Supported scope

Self-compilation identity and functional tests are not a complete correctness proof or standards certification. See Limits for capacities and restrictions.

Technical documentation

Topic Document
Seed decoding and staged bootstrapping Bootstrap design
Stage commands and validation steps Walkthrough
Application compilation and linking Usage
Source organization and toolchain composition Toolchain source guide
.c1o symbols and relocations Object format
Mathematical functions and internal algorithms Technical documentation

Cleaning and rebuilding

Close examples, wait for builds and tests to finish, and back up any artifacts or logs you need before running:

# Preview, clean, then rebuild from the seed
powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File .\clean-all.ps1 -WhatIf
powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File .\clean-all.ps1
powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File .\build-all.ps1

Cleanup is limited to these default output locations; it does not remove source or documentation or change system settings:

Do not store handwritten files there. These directories are removed in full, including any .c1-build-* children. Manage custom build directories, USAGE examples, and .c1-build-* directories outside this list yourself; the script does not empty all of work/.

The script checks cleanup paths and uses paths in SOURCES.json to protect source files; it does not check source hashes. It stops at out-of-scope paths, symbolic links, or junctions. Do not run it concurrently with a build. If locked files cause partial cleanup failure, release them and retry.

License

Source code and accompanying project documentation use the MIT License. Windows, PowerShell, and system DLLs are supplied by the user's system and are not part of the project's MIT-licensed source.

BitKindle (tombkeeper/BitKindle)

Ищем в базе…

Что это такое?BitKindle — это полноценная цепочка инструментов C для Windows x64: ассемблеры, компилятор C, библиотека времени выполнения и PE-компоновщик. Она собирает сама себя, начиная с затравки из машинного кода размером 3 584 байта, и не требует уже установленного компилятора или SDK.
Это один исполняемый файл компилятора или полноценная цепочка инструментов?Это полноценная цепочка инструментов: BitKindle включает полные исходники ассемблеров A0/A1, переходного компилятора C0, самохостящегося компилятора C1, библиотеку времени выполнения и собственный PE-компоновщик.
Нужно ли сначала установить MSVC, GCC или Windows SDK?Нет. Для сборки не нужны MSVC, GCC, Clang или Windows SDK, и никакие зависимости не скачиваются. Нужен только Windows PowerShell 5.1, который декодирует затравку и управляет сборкой.
Полностью ли компилятор соответствует стандарту C99?Нет. Он поддерживает C89 и многие возможности C99 (VLA, комплексную арифметику, составные литералы и др.), но не заявляет полного соответствия C99. Кроме того, он не умеет связываться с общими заголовками Windows SDK и со стандартными файлами COFF .obj/.lib.
На какой версии Windows это работает?Нужна Windows x64 с Windows PowerShell 5.1. Проверенная среда — Windows 10 x64.
Вся система распространяется под лицензией MIT?Исходный код и документация распространяются под лицензией MIT. Однако Windows, PowerShell и системные DLL, которые используются при сборке и запуске, берутся из системы пользователя и на них эта лицензия не распространяется.
Для чего нужна затравка размером 3 584 байта?Это минимальная отправная точка из машинного кода, которую PowerShell декодирует первой. Затем все последующие ассемблеры, этапы компилятора и компоновщик собираются инструментами, созданными этой затравкой, без участия какого-либо внешнего компилятора.
Какие примеры программ входят в состав BitKindle?Демо hello-world/argv, minicurl (загружает содержимое по HTTP/TLS через WinHTTP) и игра в духе Mario с боковой прокруткой, управлением с клавиатуры, столкновениями и графикой GDI, полностью написанная на C.
Может ли BitKindle подключаться к обычным библиотекам Windows?Он создаёт PE-файлы Windows x64 с явными импортами DLL, используя собственный формат объектов .c1o, но не поддерживает общие заголовки Windows SDK и стандартные файлы COFF .obj/.lib. Поэтому существующие проекты C с открытым исходным кодом, возможно, придётся адаптировать.
Сколько места на диске нужно для полной сборки?Для полного режима сборки и тестирования -Full требуется около 5 GiB свободного места. Кроме того, запускаются регрессионные тесты этапов и дополнительные наборы тестов примеров.
Какие есть похожие проекты?gcc, blaze, raddebugger, scriptc, porffor, fil-c, goose, compiler
Автор
tombkeeper
Размер
5.1 MB
Звёзды
218
Обновлён
КоммитOct 20
Возраст
29 д
Коммиты · 90 дней