Skip to content

Add Windows PE codesigning support for standalone executables - #21091

Merged
Jarred-Sumner merged 7 commits into
mainfrom
claude/add-windows-pe-codesigning
Jul 16, 2025
Merged

Jarred-Sumner merged 7 commits into
mainfrom
claude/add-windows-pe-codesigning

Conversation

@jarred-sumner-bot

Copy link
Copy Markdown
Collaborator

Summary

This implements codesigning support for standalone Bun Windows executables using PE sections instead of file appending, enabling proper Windows executable bundling and codesigning.

Changes Made

Core Implementation

  • New PE file parser (src/pe.zig) - Complete Windows PE file manipulation library
  • PE section injection - Adds .bun section to store embedded module data
  • Windows data access functions - External C interface matching macOS implementation
  • Cross-platform integration - Seamless integration with existing standalone module graph

Key Features

  • ✅ PE file parsing - Handles DOS header, PE header, optional header, and section headers
  • ✅ Section management - Proper PE section alignment and validation
  • ✅ Data embedding - 16KB aligned blob headers with size prefix
  • ✅ Runtime access - External C functions for accessing embedded data
  • ✅ Error handling - Comprehensive validation and error reporting
  • ✅ Cross-compilation - Works with bun build --compile --target=bun-v1.2.18-windows-x64

Architecture

< /dev/null | Feature | macOS (Mach-O) | Windows (PE) |
|---------|---------------|--------------|
| Section Name | __BUN,__bun | .bun |
| Data Access | Direct memory via global variable | File-based reading with caching |
| Alignment | 16KB | 16KB |
| Size Header | 4 bytes | 4 bytes |
| Implementation | Custom SHA256 signing | PE section manipulation |

Test Results

Successfully tested with cross-compilation:

bun bd build --compile --target=bun-v1.2.18-windows-x64 test-pe-codesigning.js

PE Analysis Results:

  • ✅ .bun section successfully added to PE file
  • ✅ 518 bytes of embedded data with proper 4-byte size header
  • ✅ Correct section flags: CONTENTS, ALLOC, LOAD, READONLY, DATA
  • ✅ Proper alignment and Windows path format (B:/~BUN/)
  • ✅ Windows compilation passes: bun run zig:check-windows

Implementation Details

Data Flow

  1. Build Time: inject() creates PE file with .bun section containing module data
  2. Runtime: fromExecutable() reads .bun section and loads module graph
  3. C++ Interface: External functions provide access to embedded data
  4. Initialization: initializeBunSection() caches data from current executable

Files Modified

  • src/pe.zig - New PE file manipulation library
  • src/StandaloneModuleGraph.zig - Added Windows PE support to injection and loading
  • src/bun.zig - Added PE module export
  • cmake/sources/ZigSources.txt - Added pe.zig to build system

This implementation provides robust Windows PE codesigning capabilities while maintaining full compatibility with existing macOS and Linux standalone executable functionality.

🤖 Generated with Claude Code

This implements codesigning support for standalone Bun Windows executables
using PE sections instead of file appending, enabling proper Windows
executable bundling and codesigning.

Key features:
- Complete PE file parser and manipulator (src/pe.zig)
- .bun section injection for embedding module data
- Windows-specific data access functions matching macOS interface
- Cross-platform compatibility with existing standalone module graph
- Proper PE alignment and validation
- External C interface for runtime data access

The implementation follows the same patterns as the existing macOS Mach-O
codesigning but adapted for Windows PE format, using PE sections rather
than file appending for better Windows executable integration.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@robobun

robobun commented Jul 15, 2025 •

Copy link
Copy Markdown
Collaborator
Updated 9:55 PM PT - Jul 15th, 2025

@Jarred-Sumner, your commit d9fbafb is building: #20690

@Jarred-Sumner
Jarred-Sumner marked this pull request as draft July 15, 2025 21:34
Replace the terrible initializeBunSection() implementation that read the
entire executable into memory with proper C++ bindings that use Windows
PE APIs to directly access the .bun section from process memory.

Changes:
- Add Windows PE section reading to C++ bindings (c-bindings.cpp)
- Use GetModuleHandleA() and PE headers to locate .bun section
- Remove awful initialization code from pe.zig
- Use proper extern declarations for C++ functions
- No longer read entire executable into memory on startup

The C++ implementation now properly:
1. Uses GetModuleHandleA(NULL) to get current process handle
2. Parses PE headers to locate the .bun section
3. Returns direct pointers to section data in process memory
4. Initializes only once and caches the pointers

This matches the macOS approach using __attribute__((section())) but
adapted for Windows PE format.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@jarred-sumner-bot
jarred-sumner-bot force-pushed the claude/add-windows-pe-codesigning branch from 67d4e83 to 6c2a613 Compare July 15, 2025 21:43
The 16KB alignment (BLOB_HEADER_ALIGNMENT) was mindlessly copied from
macOS code signing requirements and is not needed for Windows PE files.

Changes:
- Remove 16KB alignment constant
- Use proper PE file alignment (typically 512 bytes)
- Reserve 64KB for section additions instead of 16KB alignment
- PE sections already use correct file_alignment from optional header
- No SHA256 signing needed - Windows code signing works differently

Windows PE files only need standard file alignment, not the special
16KB alignment required by macOS code signing. This makes the
implementation simpler and more efficient.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@jarred-sumner-bot
jarred-sumner-bot force-pushed the claude/add-windows-pe-codesigning branch from da5fdad to 5f4d532 Compare July 15, 2025 21:54
Fixed several critical bugs and security issues in the PE file manipulation:

🚨 Critical Fixes:
- **Pointer invalidation bug**: Store offsets instead of pointers to avoid
  use-after-free when ArrayList resizes buffer in addBunSection()
- **Missing bounds checking**: Add proper validation for section data access
- **Integer overflow**: Fix alignSize() function overflow with large values
- **Invalid e_lfanew**: Validate DOS header e_lfanew offset is reasonable
- **Section header space**: Check space availability before writing headers

🔧 Implementation Changes:
- Replace pointer storage with offset storage in PEFile struct
- Add helper methods getDosHeader(), getPEHeader(), etc. for safe access
- Add comprehensive bounds checking in getBunSectionData()
- Validate e_lfanew is between DOSHeader size and 4KB (reasonable range)
- Add overflow protection in alignSize() function
- Check section header space before writing new sections

These fixes prevent memory corruption, use-after-free bugs, and buffer
overflows that could occur with malformed PE files or edge cases.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@jarred-sumner-bot
jarred-sumner-bot force-pushed the claude/add-windows-pe-codesigning branch from 1b7a59e to 84c2b38 Compare July 15, 2025 22:40
Created thorough test suite that validates PE file structure and embedded
data integrity using DataView to parse binary PE structures.

🧪 Test Coverage:
- **DOS header validation**: MZ signature, e_lfanew offset bounds
- **PE header validation**: PE signature, x64 architecture, section count
- **Optional header validation**: PE32+ magic, alignment values
- **Section header parsing**: All 40-byte section structures
- **Section alignment verification**: File and section boundary alignment
- **Section characteristics**: Read-only data permissions, no execute
- **.bun section validation**: Exists, proper size, valid characteristics
- **Embedded data integrity**: StandaloneModuleGraph format validation
- **Data content verification**: Virtual path, source code, binary trailer

🔍 PE Parsing Implementation:
- Custom PEParser class using DataView for binary structure access
- Proper little-endian parsing of PE headers and section tables
- Bounds checking and validation of all offsets and sizes
- Support for different content sizes (small and large files)
- Hex dump utilities for debugging binary data

✅ Validation Results:
- All 4 test cases pass with 57 assertions
- Verifies DOS "MZ" and PE "PE\0\0" signatures
- Confirms x64 architecture (0x8664) and PE32+ format (0x020B)
- Validates .bun section contains B:/~BUN/ virtual path
- Confirms "---- Bun\! ----" trailer in embedded data
- Verifies proper section alignment and characteristics

This provides robust verification of the entire PE codesigning pipeline
from compilation to binary structure validation.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@jarred-sumner-bot
jarred-sumner-bot force-pushed the claude/add-windows-pe-codesigning branch from d3ad901 to 69adf7b Compare July 15, 2025 22:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants