Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
b67a063
Introduce bytecode caching
Jarred-Sumner Sep 28, 2024
0cdd905
Fix makefile for building webkit
Jarred-Sumner Sep 29, 2024
5ea6e1d
we are caching
Jarred-Sumner Sep 29, 2024
3342dca
Several bugfixes to CommonJS bundling
Jarred-Sumner Sep 30, 2024
d8a352e
Update default.test.ts
Jarred-Sumner Sep 30, 2024
4f27596
Update SetupWebKit.cmake
Jarred-Sumner Sep 30, 2024
75bd6f8
We resolve require.resolve
Jarred-Sumner Sep 30, 2024
cb6849a
Emit use strict
Jarred-Sumner Sep 30, 2024
b499fd2
POSSIBLY BREAKING: don't create module namespace object wrapper
Jarred-Sumner Sep 30, 2024
d2f7676
Fix tests
Jarred-Sumner Sep 30, 2024
5c410dd
Set bytecode cache to a known version
Jarred-Sumner Sep 30, 2024
38b6d52
Update ZigGlobalObject.cpp
Jarred-Sumner Sep 30, 2024
aa20532
Ban TLA in CJS
Jarred-Sumner Sep 30, 2024
9059d89
Support bytecode & cjs in `bun build --compile`
Jarred-Sumner Sep 30, 2024
478001d
works now.
Jarred-Sumner Sep 30, 2024
be9352e
Update bundler_compile.test.ts
Jarred-Sumner Sep 30, 2024
20a3a46
Update some docs
Jarred-Sumner Sep 30, 2024
726b717
Update executables.md
Jarred-Sumner Sep 30, 2024
b847a4e
Update index.md
Jarred-Sumner Sep 30, 2024
9b3dda3
oops
Jarred-Sumner Sep 30, 2024
f1c5a35
Add an API test
Jarred-Sumner Sep 30, 2024
7b9cb2e
Update cli.zig
Jarred-Sumner Sep 30, 2024
8b1c0ed
cjs
Jarred-Sumner Sep 30, 2024
5d9f9e9
Stricter validations
Jarred-Sumner Oct 1, 2024
3fd10bb
Comment
Jarred-Sumner Oct 1, 2024
3a0c81c
Update bundle_v2.zig
Jarred-Sumner Oct 1, 2024
1705d95
Update src/bun.js/module_loader.zig
Jarred-Sumner Oct 1, 2024
df43b7e
Update expectBundled.ts
Jarred-Sumner Oct 1, 2024
eeaaf19
Update build_command.zig
Jarred-Sumner Oct 1, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 9 additions & 18 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ BUN_RELEASE_BIN = $(PACKAGE_DIR)/bun
PRETTIER ?= $(shell which prettier 2>/dev/null || echo "./node_modules/.bin/prettier")
ESBUILD = "$(shell which esbuild 2>/dev/null || echo "./node_modules/.bin/esbuild")"
DSYMUTIL ?= $(shell which dsymutil 2>/dev/null || which dsymutil-15 2>/dev/null)
WEBKIT_DIR ?= $(realpath src/bun.js/WebKit)
WEBKIT_DIR ?= $(realpath vendor/WebKit)
WEBKIT_RELEASE_DIR ?= $(WEBKIT_DIR)/WebKitBuild/Release
WEBKIT_DEBUG_DIR ?= $(WEBKIT_DIR)/WebKitBuild/Debug
WEBKIT_RELEASE_DIR_LTO ?= $(WEBKIT_DIR)/WebKitBuild/ReleaseLTO
Expand Down Expand Up @@ -138,8 +138,8 @@ endif
SED = $(shell which gsed 2>/dev/null || which sed 2>/dev/null)

BUN_DIR ?= $(shell dirname $(realpath $(firstword $(MAKEFILE_LIST))))
BUN_DEPS_DIR ?= $(shell pwd)/src/deps
BUN_DEPS_OUT_DIR ?= $(shell pwd)/build/bun-deps
BUN_DEPS_DIR ?= $(shell pwd)/vendor
BUN_DEPS_OUT_DIR ?= $(shell pwd)/build/release
CPU_COUNT = 2
ifeq ($(OS_NAME),darwin)
CPU_COUNT = $(shell sysctl -n hw.logicalcpu)
Expand Down Expand Up @@ -689,19 +689,10 @@ assert-deps:
@test $(shell cargo --version | awk '{print $$2}' | cut -d. -f2) -gt 57 || (echo -e "ERROR: cargo version must be at least 1.57."; exit 1)
@echo "You have the dependencies installed! Woo"

# the following allows you to run `make submodule` to update or init submodules. but we will exclude webkit
# unless you explicitly clone it yourself (a huge download)
SUBMODULE_NAMES=$(shell cat .gitmodules | grep 'path = ' | awk '{print $$3}')
ifeq ("$(wildcard src/bun.js/WebKit/.git)", "")
SUBMODULE_NAMES := $(filter-out src/bun.js/WebKit, $(SUBMODULE_NAMES))
endif

.PHONY: init-submodules
init-submodules: submodule # (backwards-compatibility alias)

.PHONY: submodule
submodule: ## to init or update all submodules
git submodule update --init --recursive --progress --depth=1 --checkout $(SUBMODULE_NAMES)

.PHONY: build-obj
build-obj:
Expand Down Expand Up @@ -804,7 +795,7 @@ cls:
@echo -e "\n\n---\n\n"

jsc-check:
@ls $(JSC_BASE_DIR) >/dev/null 2>&1 || (echo -e "Failed to access WebKit build. Please compile the WebKit submodule using the Dockerfile at $(shell pwd)/src/javascript/WebKit/Dockerfile and then copy from /output in the Docker container to $(JSC_BASE_DIR). You can override the directory via JSC_BASE_DIR. \n\n DOCKER_BUILDKIT=1 docker build -t bun-webkit $(shell pwd)/src/bun.js/WebKit -f $(shell pwd)/src/bun.js/WebKit/Dockerfile --progress=plain\n\n docker container create bun-webkit\n\n # Get the container ID\n docker container ls\n\n docker cp DOCKER_CONTAINER_ID_YOU_JUST_FOUND:/output $(JSC_BASE_DIR)" && exit 1)
@ls $(JSC_BASE_DIR) >/dev/null 2>&1 || (echo -e "Failed to access WebKit build. Please compile the WebKit submodule using the Dockerfile at $(shell pwd)/src/javascript/WebKit/Dockerfile and then copy from /output in the Docker container to $(JSC_BASE_DIR). You can override the directory via JSC_BASE_DIR. \n\n DOCKER_BUILDKIT=1 docker build -t bun-webkit $(shell pwd)/vendor/WebKit -f $(shell pwd)/vendor/WebKit/Dockerfile --progress=plain\n\n docker container create bun-webkit\n\n # Get the container ID\n docker container ls\n\n docker cp DOCKER_CONTAINER_ID_YOU_JUST_FOUND:/output $(JSC_BASE_DIR)" && exit 1)
@ls $(JSC_INCLUDE_DIR) >/dev/null 2>&1 || (echo "Failed to access WebKit include directory at $(JSC_INCLUDE_DIR)." && exit 1)
@ls $(JSC_LIB) >/dev/null 2>&1 || (echo "Failed to access WebKit lib directory at $(JSC_LIB)." && exit 1)

Expand Down Expand Up @@ -945,7 +936,7 @@ jsc-bindings: headers bindings

.PHONY: clone-submodules
clone-submodules:
git -c submodule."src/bun.js/WebKit".update=none submodule update --init --recursive --depth=1 --progress
git -c submodule."vendor/WebKit".update=none submodule update --init --recursive --depth=1 --progress


.PHONY: headers
Expand Down Expand Up @@ -1265,7 +1256,7 @@ jsc-build-mac-compile:
-DENABLE_STATIC_JSC=ON \
-DENABLE_SINGLE_THREADED_VM_ENTRY_SCOPE=ON \
-DALLOW_LINE_AND_COLUMN_NUMBER_IN_BUILTINS=ON \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DUSE_THIN_ARCHIVES=OFF \
-DBUN_FAST_TLS=ON \
-DENABLE_FTL_JIT=ON \
Expand All @@ -1277,7 +1268,7 @@ jsc-build-mac-compile:
$(WEBKIT_DIR) \
$(WEBKIT_RELEASE_DIR) && \
CFLAGS="$(CFLAGS) -ffat-lto-objects" CXXFLAGS="$(CXXFLAGS) -ffat-lto-objects" \
cmake --build $(WEBKIT_RELEASE_DIR) --config Release --target jsc
cmake --build $(WEBKIT_RELEASE_DIR) --config RelWithDebInfo --target jsc

.PHONY: jsc-build-mac-compile-lto
jsc-build-mac-compile-lto:
Expand Down Expand Up @@ -1379,7 +1370,7 @@ jsc-build-linux-compile-config-debug:
$(WEBKIT_DEBUG_DIR)

# If you get "Error: could not load cache"
# run rm -rf src/bun.js/WebKit/CMakeCache.txt
# run rm -rf vendor/WebKit/CMakeCache.txt
.PHONY: jsc-build-linux-compile-build
jsc-build-linux-compile-build:
mkdir -p $(WEBKIT_RELEASE_DIR) && \
Expand Down Expand Up @@ -1414,7 +1405,7 @@ jsc-build-copy-debug:
cp $(WEBKIT_DEBUG_DIR)/lib/libbmalloc.a $(BUN_DEPS_OUT_DIR)/libbmalloc.a

clean-jsc:
cd src/bun.js/WebKit && rm -rf **/CMakeCache.txt **/CMakeFiles && rm -rf src/bun.js/WebKit/WebKitBuild
cd vendor/WebKit && rm -rf **/CMakeCache.txt **/CMakeFiles && rm -rf vendor/WebKit/WebKitBuild
clean-bindings:
rm -rf $(OBJ_DIR)/*.o $(DEBUG_OBJ_DIR)/*.o $(DEBUG_OBJ_DIR)/webcore/*.o $(DEBUG_BINDINGS_OBJ) $(OBJ_DIR)/webcore/*.o $(BINDINGS_OBJ) $(OBJ_DIR)/*.d $(DEBUG_OBJ_DIR)/*.d

Expand Down
2 changes: 1 addition & 1 deletion cmake/tools/SetupWebKit.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ option(WEBKIT_VERSION "The version of WebKit to use")
option(WEBKIT_LOCAL "If a local version of WebKit should be used instead of downloading")

if(NOT WEBKIT_VERSION)
set(WEBKIT_VERSION 4a2db3254a9535949a5d5380eb58cf0f77c8e15a)
set(WEBKIT_VERSION 76798f7b2fb287ee9f1ecce98bae895a2d026d93)
endif()

if(WEBKIT_LOCAL)
Expand Down
2 changes: 1 addition & 1 deletion src/bun.js/bindings/CommonJSModuleRecord.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -763,7 +763,7 @@ void populateESMExports(
bool ignoreESModuleAnnotation)
{
auto& vm = globalObject->vm();
Identifier esModuleMarker = builtinNames(vm).__esModulePublicName();
const Identifier& esModuleMarker = builtinNames(vm).__esModulePublicName();

// Bun's intepretation of the "__esModule" annotation:
//
Expand Down
119 changes: 111 additions & 8 deletions src/bun.js/bindings/ZigSourceProvider.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
#include <wtf/Scope.h>
#include <wtf/text/StringHash.h>
#include <sys/stat.h>
#include <JavaScriptCore/SourceCodeKey.h>
#include <mimalloc.h>
#include <JavaScriptCore/CodeCache.h>

extern "C" void RefString__free(void*, void*, unsigned);

Expand Down Expand Up @@ -91,14 +94,40 @@ Ref<SourceProvider> SourceProvider::create(
// https://github.com/oven-sh/bun/issues/9521
}

auto provider = adoptRef(*new SourceProvider(
globalObject->isThreadLocalDefaultGlobalObject ? globalObject : nullptr,
resolvedSource,
string.isNull() ? *StringImpl::empty() : *string.impl(),
JSC::SourceTaintedOrigin::Untainted,
toSourceOrigin(sourceURLString, isBuiltin),
sourceURLString.impl(), TextPosition(),
sourceType));
const auto getProvider = [&]() -> Ref<SourceProvider> {
if (resolvedSource.bytecode_cache != nullptr) {
Ref<JSC::CachedBytecode> bytecode = JSC::CachedBytecode::create(std::span<uint8_t>(resolvedSource.bytecode_cache, resolvedSource.bytecode_cache_size), [](const void* ptr) {
mi_free(const_cast<void*>(ptr));
},
{});
std::optional<JSC::SourceCodeKey> optionalSourceCodeKey = JSC::decodeSourceCodeKey(globalObject->vm(), bytecode.copyRef());

if (optionalSourceCodeKey.has_value()) {
JSC::SourceCodeKey sourceCodeKey = optionalSourceCodeKey.value();
auto provider = adoptRef(*new SourceProvider(
globalObject->isThreadLocalDefaultGlobalObject ? globalObject : nullptr,
resolvedSource,
string.isNull() ? *StringImpl::empty() : *string.impl(),
JSC::SourceTaintedOrigin::Untainted,
toSourceOrigin(sourceURLString, isBuiltin),
sourceURLString.impl(), TextPosition(),
sourceCodeKey.source().provider().sourceType()));
provider->m_cachedBytecode = WTFMove(bytecode);
return provider;
}
}

return adoptRef(*new SourceProvider(
globalObject->isThreadLocalDefaultGlobalObject ? globalObject : nullptr,
resolvedSource,
string.isNull() ? *StringImpl::empty() : *string.impl(),
JSC::SourceTaintedOrigin::Untainted,
toSourceOrigin(sourceURLString, isBuiltin),
sourceURLString.impl(), TextPosition(),
sourceType));
};

auto provider = getProvider();

if (shouldGenerateCodeCoverage) {
ByteRangeMapping__generate(Bun::toString(provider->sourceURL()), Bun::toString(provider->source().toStringWithoutCopying()), provider->asID());
Expand All @@ -111,6 +140,11 @@ Ref<SourceProvider> SourceProvider::create(
return provider;
}

StringView SourceProvider::source() const
{
return StringView(m_source.get());
}

SourceProvider::~SourceProvider()
{
if (m_resolvedSource.already_bundled) {
Expand All @@ -119,6 +153,75 @@ SourceProvider::~SourceProvider()
}
}

extern "C" bool generateCachedModuleByteCodeFromSourceCode(BunString* sourceProviderURL, const LChar* inputSourceCode, size_t inputSourceCodeSize, const uint8_t** outputByteCode, size_t* outputByteCodeSize)
{
std::span<const LChar> sourceCodeSpan(inputSourceCode, inputSourceCodeSize);
JSC::SourceCode sourceCode = JSC::makeSource(WTF::String(sourceCodeSpan), toSourceOrigin(sourceProviderURL->toWTFString(), false), JSC::SourceTaintedOrigin::Untainted);
auto heapSize = JSC::HeapType::Small;

JSC::VM& vm = JSC::VM::create(heapSize).leakRef();
// This must happen before JSVMClientData::create
vm.heap.acquireAccess();
JSC::JSLockHolder locker(vm);
LexicallyScopedFeatures lexicallyScopedFeatures = StrictModeLexicallyScopedFeature;
JSParserScriptMode scriptMode = JSParserScriptMode::Module;
EvalContextType evalContextType = EvalContextType::None;

ParserError parserError;
UnlinkedModuleProgramCodeBlock* unlinkedCodeBlock = JSC::recursivelyGenerateUnlinkedCodeBlockForModuleProgram(vm, sourceCode, lexicallyScopedFeatures, scriptMode, {}, parserError, evalContextType);
if (parserError.isValid())
return false;
if (!unlinkedCodeBlock)
return false;

auto key = JSC::sourceCodeKeyForSerializedModule(vm, sourceCode);

RefPtr<JSC::CachedBytecode> cachedBytecode = JSC::encodeCodeBlock(vm, key, unlinkedCodeBlock);
if (!cachedBytecode)
return false;

cachedBytecode->ref();
*outputByteCode = cachedBytecode->span().data();
*outputByteCodeSize = cachedBytecode->span().size();

return true;
}

extern "C" bool generateCachedCommonJSProgramByteCodeFromSourceCode(BunString* sourceProviderURL, const LChar* inputSourceCode, size_t inputSourceCodeSize, const uint8_t** outputByteCode, size_t* outputByteCodeSize)
{
std::span<const LChar> sourceCodeSpan(inputSourceCode, inputSourceCodeSize);

JSC::SourceCode sourceCode = JSC::makeSource(WTF::String(sourceCodeSpan), toSourceOrigin(sourceProviderURL->toWTFString(), false), JSC::SourceTaintedOrigin::Untainted);
auto heapSize = JSC::HeapType::Small;

JSC::VM& vm = JSC::VM::create(heapSize).leakRef();
// This must happen before JSVMClientData::create
vm.heap.acquireAccess();
JSC::JSLockHolder locker(vm);
LexicallyScopedFeatures lexicallyScopedFeatures = NoLexicallyScopedFeatures;
JSParserScriptMode scriptMode = JSParserScriptMode::Classic;
EvalContextType evalContextType = EvalContextType::None;

ParserError parserError;
UnlinkedProgramCodeBlock* unlinkedCodeBlock = JSC::recursivelyGenerateUnlinkedCodeBlockForProgram(vm, sourceCode, lexicallyScopedFeatures, scriptMode, {}, parserError, evalContextType);
if (parserError.isValid())
return false;
if (!unlinkedCodeBlock)
return false;

auto key = JSC::sourceCodeKeyForSerializedProgram(vm, sourceCode);

RefPtr<JSC::CachedBytecode> cachedBytecode = JSC::encodeCodeBlock(vm, key, unlinkedCodeBlock);
if (!cachedBytecode)
return false;

cachedBytecode->ref();
*outputByteCode = cachedBytecode->span().data();
*outputByteCodeSize = cachedBytecode->span().size();

return true;
}

unsigned SourceProvider::hash() const
{
if (m_hash) {
Expand Down
6 changes: 3 additions & 3 deletions src/bun.js/bindings/ZigSourceProvider.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ class SourceProvider final : public JSC::SourceProvider {
bool isBuiltIn = false);
~SourceProvider();
unsigned hash() const override;
StringView source() const override { return StringView(m_source.get()); }
StringView source() const override;

RefPtr<JSC::CachedBytecode> cachedBytecode()
RefPtr<JSC::CachedBytecode> cachedBytecode() const final
{
return nullptr;
return m_cachedBytecode.copyRef();
};

void updateCache(const UnlinkedFunctionExecutable* executable, const SourceCode&,
Expand Down
2 changes: 2 additions & 0 deletions src/bun.js/bindings/exports.zig
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,8 @@ pub const ResolvedSource = extern struct {
/// This is for source_code
source_code_needs_deref: bool = true,
already_bundled: bool = false,
bytecode_cache: ?[*]u8 = null,
bytecode_cache_size: usize = 0,

pub const Tag = @import("ResolvedSourceTag").ResolvedSourceTag;
};
Expand Down
2 changes: 2 additions & 0 deletions src/bun.js/bindings/headers-handwritten.h
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ typedef struct ResolvedSource {
uint32_t tag;
bool needsDeref;
bool already_bundled;
uint8_t* bytecode_cache;
size_t bytecode_cache_size;
} ResolvedSource;
static const uint32_t ResolvedSourceTagPackageJSONTypeModule = 1;
typedef union ErrorableResolvedSourceResult {
Expand Down
2 changes: 1 addition & 1 deletion src/bun.js/javascript.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2752,7 +2752,7 @@ pub const VirtualMachine = struct {
JSC.JSValue.fromCell(promise).ensureStillAlive();
return promise;
} else {
const promise = JSModuleLoader.loadAndEvaluateModule(this.global, &String.init(this.main)) orelse return error.JSError;
const promise = JSModuleLoader.loadAndEvaluateModule(this.global, &String.fromBytes(this.main)) orelse return error.JSError;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change looks identical to the original

this.pending_internal_promise = promise;
JSC.JSValue.fromCell(promise).ensureStillAlive();

Expand Down
14 changes: 12 additions & 2 deletions src/bun.js/module_loader.zig
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,7 @@ pub const RuntimeTranspilerStore = struct {
setBreakPointOnFirstLine(),
.runtime_transpiler_cache = if (!JSC.RuntimeTranspilerCache.is_disabled) &cache else null,
.remove_cjs_module_wrapper = is_main and vm.module_loader.eval_source != null,
.allow_bytecode_cache = true,
};

defer {
Expand Down Expand Up @@ -573,15 +574,19 @@ pub const RuntimeTranspilerStore = struct {
return;
}

if (parse_result.already_bundled) {
if (parse_result.already_bundled != .none) {
const duped = String.createUTF8(specifier);
const bytecode_slice = parse_result.already_bundled.bytecodeSlice();
this.resolved_source = ResolvedSource{
.allocator = null,
.source_code = bun.String.createLatin1(parse_result.source.contents),
.specifier = duped,
.source_url = duped.createIfDifferent(path.text),
.already_bundled = true,
.hash = 0,
.bytecode_cache = if (bytecode_slice.len > 0) bytecode_slice.ptr else null,
.bytecode_cache_size = if (bytecode_slice.len > 0) bytecode_slice.len else 0,
Comment thread
Jarred-Sumner marked this conversation as resolved.
Resolved
.is_commonjs_module = parse_result.already_bundled.isCommonJS(),
};
this.resolved_source.source_code.ensureHash();
return;
Expand Down Expand Up @@ -1615,6 +1620,7 @@ pub const ModuleLoader = struct {
.allow_commonjs = true,
.inject_jest_globals = jsc_vm.bundler.options.rewrite_jest_for_tests and is_main,
.keep_json_and_toml_as_one_statement = true,
.allow_bytecode_cache = true,
.set_breakpoint_on_first_line = is_main and
jsc_vm.debugger != null and
jsc_vm.debugger.?.set_breakpoint_on_first_line and
Expand Down Expand Up @@ -1760,14 +1766,18 @@ pub const ModuleLoader = struct {
};
}

if (parse_result.already_bundled) {
if (parse_result.already_bundled != .none) {
const bytecode_slice = parse_result.already_bundled.bytecodeSlice();
return ResolvedSource{
.allocator = null,
.source_code = bun.String.createLatin1(parse_result.source.contents),
.specifier = input_specifier,
.source_url = input_specifier.createIfDifferent(path.text),
.already_bundled = true,
.hash = 0,
.bytecode_cache = if (bytecode_slice.len > 0) bytecode_slice.ptr else null,
.bytecode_cache_size = if (bytecode_slice.len > 0) bytecode_slice.len else 0,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
.bytecode_cache_size = if (bytecode_slice.len > 0) bytecode_slice.len else 0,
.bytecode_cache_size = bytecode_slice.len,

.is_commonjs_module = parse_result.already_bundled.isCommonJS(),
};
}

Expand Down
2 changes: 2 additions & 0 deletions src/bun.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3820,3 +3820,5 @@ pub fn WeakPtr(comptime T: type, comptime weakable_field: std.meta.FieldEnum(T))
}
};
}

pub const bytecode_extension = ".bun";
Loading