Compare commits

...

106 Commits

Author SHA1 Message Date
Jarred Sumner
52d47c24dc Merge branch 'jarred/prepare-for-libuv' of https://github.com/oven-sh/bun into jarred/prepare-for-libuv 2023-09-09 15:13:58 -08:00
Jarred Sumner
99c92d2b81 Update index.ts 2023-09-09 16:13:45 -07:00
Jarred Sumner
242ab4445b bump 2023-09-09 16:04:00 -07:00
Jarred Sumner
7f6bbce191 Merge branch 'main' into jarred/prepare-for-libuv 2023-09-09 15:03:47 -08:00
Jarred SUmner
fb86c1bdfe [dave]: fix webcrypto crash 2023-09-07 09:03:18 -07:00
Jarred Sumner
f44c2b65a3 hm 2023-09-07 08:58:47 -07:00
Jarred Sumner
7177cb0803 Merge branch 'main' into jarred/prepare-for-libuv 2023-09-07 06:14:50 -07:00
Jarred Sumner
69696793d5 Make sure we remove libusockets is removed 2023-09-07 05:54:45 -07:00
Jarred SUmner
605477f49a Fix some test failures 2023-09-07 05:52:36 -07:00
Jarred SUmner
ce16029183 Fix sqlite test failures 2023-09-07 04:46:53 -07:00
Jarred Sumner
c645342a74 Update mimalloc 2023-09-07 01:54:24 -08:00
Jarred Sumner
48cdfd6685 Merge branch 'jarred/prepare-for-libuv' of https://github.com/oven-sh/bun into jarred/prepare-for-libuv 2023-09-07 01:53:49 -08:00
Jarred Sumner
9452ade912 more 2023-09-07 01:53:41 -08:00
Jarred Sumner
f7ce24895a Set permissions 2023-09-07 00:38:41 -07:00
Jarred Sumner
cffdacc5fa Merge branch 'jarred/prepare-for-libuv' of https://github.com/oven-sh/bun into jarred/prepare-for-libuv 2023-09-06 23:09:49 -08:00
Jarred Sumner
dbd57f426c Update feature_flags.zig 2023-09-06 23:47:02 -07:00
Jarred Sumner
497d546048 Revert "avoid duplicate symbols"
This reverts commit 4ac6ca8700.
2023-09-06 23:06:47 -07:00
Jarred Sumner
19a4df3c52 Revert "avoid undefined symbols"
This reverts commit ca835b726f.
2023-09-06 23:06:41 -07:00
Jarred Sumner
c7e93c1376 Update response.zig 2023-09-06 22:44:09 -07:00
Jarred Sumner
9e82e040dc Merge branch 'jarred/prepare-for-libuv' of https://github.com/oven-sh/bun into jarred/prepare-for-libuv 2023-09-06 21:41:36 -08:00
Jarred Sumner
b6a4609a73 Update feature_flags.zig 2023-09-06 22:38:10 -07:00
Jarred Sumner
0a968a66c2 churn 2023-09-06 22:37:41 -07:00
Jarred Sumner
61bb92b7bc Merge remote-tracking branch 'origin' into jarred/prepare-for-libuv 2023-09-06 22:37:24 -07:00
Jarred Sumner
4b5233fc3a feat(fetch) rejectUnauthorized and checkServerIdentity (#4514)
* enable root certs on fetch

* rebase

* fix lookup

* some fixes and improvements

* fmt

* more fixes

* more fixes

* check detached onHandshake

* fix promise case

* fix cert non-Native

* add fetch tls tests

* more one test
2023-09-06 22:33:55 -07:00
Birk Skyum
99219d5e1c Update nodejs compat docs cp/cpSync/watchFile/unwatchFile (#4525) 2023-09-06 22:32:27 -07:00
Ashcon Partovi
70ec9afa46 Add bun-types to 'bun fmt' script 2023-09-06 22:32:26 -07:00
Ashcon Partovi
eb316e7197 Add types for watchFile and unwatchFile 2023-09-06 22:32:26 -07:00
Ashcon Partovi
02ba25c103 Add types for cp and cpSync 2023-09-06 22:32:26 -07:00
Ashcon Partovi
2b6f297c0d Remove issue template for install
It's not used, and use the bug issue instead.
2023-09-06 22:32:26 -07:00
Jarred Sumner
dc8d70ab02 Merge branch 'main' into jarred/prepare-for-libuv 2023-09-06 21:27:16 -08:00
Jarred Sumner
b38b345184 Merge branch 'jarred/prepare-for-libuv' of https://github.com/oven-sh/bun into jarred/prepare-for-libuv 2023-09-06 20:49:26 -08:00
Jarred Sumner
b7241f77fe bump 2023-09-06 20:47:06 -08:00
Dylan Conway
ca835b726f avoid undefined symbols 2023-09-06 14:24:04 -07:00
Dylan Conway
4ac6ca8700 avoid duplicate symbols 2023-09-06 14:12:06 -07:00
Jarred Sumner
bd7a2619e8 Merge branch 'jarred/prepare-for-libuv' of https://github.com/oven-sh/bun into jarred/prepare-for-libuv 2023-09-06 11:20:35 -08:00
Jarred Sumner
258615a43f fixup 2023-09-06 11:20:01 -08:00
Jarred Sumner
33d83ad6ca Update bun.zig 2023-09-06 12:09:28 -07:00
Jarred Sumner
bb9e0c2043 windows 2023-09-06 11:02:41 -08:00
Jarred Sumner
724a83de53 some clenaup 2023-09-06 10:51:32 -08:00
Jarred Sumner
db42fd3b1d Merge branch 'jarred/prepare-for-libuv' of https://github.com/oven-sh/bun into jarred/prepare-for-libuv 2023-09-06 10:31:17 -08:00
Jarred Sumner
9a485be954 ok 2023-09-06 10:29:42 -08:00
Jarred Sumner
dca6ffd4cd We have to bump the version of Debian because libarchive has a higher minimum requirement 2023-09-06 09:28:20 -07:00
Jarred Sumner
dae3887bed Undo that change 2023-09-06 09:20:30 -07:00
Jarred Sumner
6979855f42 Bummp 2023-09-06 08:59:06 -07:00
Jarred Sumner
ce4c1351bb Bump 2023-09-06 08:57:53 -07:00
Jarred Sumner
1a275c6337 small fixes 2023-09-06 08:56:16 -07:00
Jarred Sumner
666fbead09 Fixes 2023-09-06 08:42:43 -07:00
Jarred Sumner
b8329f293e Merge branch 'jarred/prepare-for-libuv' of https://github.com/oven-sh/bun into jarred/prepare-for-libuv 2023-09-06 06:48:27 -08:00
Jarred Sumner
4601b80d7c use less std.os 2023-09-06 06:48:08 -08:00
Jarred Sumner
4b58698136 Merge branch 'main' into jarred/prepare-for-libuv 2023-09-06 07:40:51 -07:00
Jarred Sumner
400bc949e6 more things work 2023-09-06 06:37:59 -08:00
Jarred Sumner
5fb23b9296 bun install progress 2023-09-06 04:18:14 -08:00
Jarred Sumner
caa3ff71fe Make require() work 2023-09-06 01:19:45 -08:00
Jarred Sumner
c33e86e1a4 Bun.serve() and much of the event loop works now 2023-09-06 00:57:25 -08:00
Jarred Sumner
e44911d4eb fetch works 2023-09-05 22:19:48 -08:00
Jarred Sumner
e7c6b1d683 fixup 2023-09-05 21:25:54 -07:00
Jarred Sumner
38849b566d Update JSSink.h 2023-09-05 21:08:50 -07:00
Jarred Sumner
831919d12a regenaret 2023-09-05 21:08:36 -07:00
Jarred Sumner
547b8453ec reb 2023-09-05 21:05:14 -07:00
Jarred Sumner
b9e5758a86 Merge branch 'main' into jarred/prepare-for-libuv 2023-09-05 19:26:45 -08:00
Jarred Sumner
27c82a6763 Many more things are starting to work. 2023-09-05 17:43:23 -08:00
Jarred Sumner
4b1d1a272a Merge branch 'main' into jarred/prepare-for-libuv 2023-09-05 05:11:46 -08:00
Jarred Sumner
ebc64f2b4d zig fmt 2023-09-05 05:11:39 -08:00
Jarred Sumner
e2d3bdd6b3 Update CMakeLists.txt 2023-09-05 05:08:44 -08:00
Jarred Sumner
f9d325cb56 quite a lot of fixes 2023-09-05 05:08:37 -08:00
Jarred Sumner
5b808d6c5c hm 2023-09-05 00:49:37 -08:00
Jarred Sumner
e84a85b020 Update .gitignore 2023-09-05 00:48:00 -08:00
Jarred Sumner
a66b766ced more 2023-09-05 00:45:51 -08:00
Jarred Sumner
04a2944eb3 further! 2023-09-05 00:44:22 -08:00
Jarred Sumner
c5ea98ae56 Update src/bun.js/bindings/headers-handwritten.h
Co-authored-by: Dylan Conway <35280289+dylan-conway@users.noreply.github.com>
2023-09-04 19:53:38 -07:00
Dylan Conway
5aa1324938 Update wtf-bindings.cpp 2023-09-04 19:43:38 -07:00
Jarred Sumner
fd97e2f17a Fixups 2023-09-04 19:17:01 -07:00
Jarred Sumner
35fdc690b7 Rename file 2023-09-04 19:17:01 -07:00
Jarred Sumner
32084dac41 hmmm 2023-09-04 10:54:50 -08:00
Jarred Sumner
6adb60197e it works 2023-09-04 10:19:29 -08:00
Jarred Sumner
a113950d41 Merge branch 'jarred/prepare-for-libuv' of https://github.com/oven-sh/bun into jarred/prepare-for-libuv 2023-09-04 08:58:06 -08:00
Jarred Sumner
dfa0bf6f5b Fix build issue 2023-09-04 08:58:04 -08:00
Jarred Sumner
c63b9aa548 Update windows.zig 2023-09-04 09:55:55 -07:00
Jarred Sumner
f40b07ad65 Update windows.zig 2023-09-04 09:55:49 -07:00
Jarred Sumner
f76f15c5e2 Add fast-ish path for bun install on Windows 2023-09-04 09:55:18 -07:00
Jarred Sumner
37d8593713 fix variosu issues 2023-09-04 05:58:03 -08:00
Jarred Sumner
3b9318794d Fix getenvZ 2023-09-04 03:07:45 -07:00
Jarred Sumner
60f1a81d06 12 mb 2023-09-04 02:42:21 -07:00
Jarred Sumner
03334de41e More 2023-09-04 00:02:19 -08:00
Jarred Sumner
36840f8ab0 Add musl polyfill for memmem on Windows 2023-09-04 00:02:07 -08:00
Jarred Sumner
2ef51cadb0 Rename Process -> BunProcess
Works around a Windows issue
2023-09-04 00:01:53 -08:00
Jarred Sumner
c9f614a2f2 theres more 2023-09-04 00:01:29 -08:00
Jarred Sumner
5b1f211110 draw the rest of the owl 2023-09-04 00:01:00 -08:00
Jarred Sumner
0ff9a10355 chunk 2023-09-03 23:57:55 -08:00
Jarred Sumner
c267a422ad Fix one of the compiler errors 2023-09-03 22:21:35 -07:00
Jarred Sumner
3de075bbae Fixup 2023-09-03 04:18:51 -07:00
Jarred Sumner
b142009fc9 Fix usockets warnings 2023-09-03 04:14:29 -07:00
Jarred Sumner
8f7f75bb2a put it in the zig file 2023-09-03 03:56:51 -07:00
Jarred Sumner
80e45451cf Update JSSQLStatement.h 2023-09-03 02:24:07 -07:00
Jarred Sumner
1d5ea13825 cmake works 2023-09-03 02:14:02 -07:00
Jarred Sumner
d5d0ffe43c more warnings 2023-09-03 00:46:46 -07:00
Jarred Sumner
8a5f27c1a7 Remove more warnings 2023-09-03 00:32:55 -07:00
Jarred Sumner
40193f8846 Fix a bunch of compiler warnings 2023-09-03 00:29:25 -07:00
Jarred Sumner
24582cc99b Update settings.json 2023-09-02 21:30:16 -07:00
Jarred Sumner
668e5ce368 Add the build scripts 2023-09-01 21:33:52 -07:00
Jarred Sumner
9c8e17e300 Bump mimalloc 2023-09-01 20:40:29 -07:00
Jarred Sumner
cbdf380493 Make compiling each dependency a shell script 2023-09-01 18:15:19 -07:00
Jarred Sumner
3c4015de26 wip 2023-08-31 03:29:03 -07:00
Jarred Sumner
69f85b59ad Update libuv.zig 2023-08-31 02:16:58 -07:00
Jarred Sumner
3775081e5a More progress 2023-08-31 02:11:04 -07:00
Jarred Sumner
a81ca0d9cc Prepare for windows event loop 2023-08-31 00:22:50 -07:00
309 changed files with 10552 additions and 5812 deletions

18
.build/base64.bash Normal file
View File

@@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -euxo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
CMAKE_FLAGS=${CMAKE_FLAGS:-}
BUN_BASE_DIR=${BUN_BASE_DIR:-$(cd $SCRIPT_DIR && cd ../ && pwd)}
BUN_DEPS_OUT_DIR=${BUN_DEPS_OUT_DIR:-$BUN_BASE_DIR/src/deps/}
BUN_DEPS_DIR=${BUN_DEPS_DIR:-$BUN_BASE_DIR/src/deps}
CCACHE_CC_FLAG=${CCACHE_CC_FLAG:-}
CFLAGS=${CFLAGS:-}
mkdir -p $BUN_DEPS_OUT_DIR
cp $BUN_DEPS_DIR/base64
make clean
cmake $CMAKE_FLAGS .
make
cp libbase64.a $BUN_DEPS_OUT_DIR/libbase64.a

22
.build/base64.ps1 Normal file
View File

@@ -0,0 +1,22 @@
$ErrorActionPreference = 'Stop' # Setting strict mode, similar to 'set -euo pipefail' in bash
$SCRIPT_DIR = Split-Path $PSScriptRoot -Parent
$CMAKE_FLAGS = $env:CMAKE_FLAGS
$BUN_BASE_DIR = if ($env:BUN_BASE_DIR) { $env:BUN_BASE_DIR } else { $SCRIPT_DIR }
$BUN_DEPS_OUT_DIR = if ($env:BUN_DEPS_OUT_DIR) { $env:BUN_DEPS_OUT_DIR } else { Join-Path $BUN_BASE_DIR 'src\deps' }
$BUN_DEPS_DIR = if ($env:BUN_DEPS_DIR) { $env:BUN_DEPS_DIR } else { Join-Path $BUN_BASE_DIR 'src\deps' }
$CCACHE_CC_FLAG = $env:CCACHE_CC_FLAG
$CPUS = if ($env:CPUS) { $env:CPUS } else { (Get-WmiObject -Class Win32_ComputerSystem).NumberOfLogicalProcessors }
$CFLAGS = $env:CFLAGS
$CXXFLAGS = $env:CXXFLAGS
# Create the output directory if it doesn't exist
if (-not (Test-Path $BUN_DEPS_OUT_DIR)) {
New-Item -ItemType Directory -Path $BUN_DEPS_OUT_DIR
}
Set-Location (Join-Path $BUN_DEPS_DIR 'base64')
cmake $CMAKE_FLAGS .
cmake --build . --clean-first --config Release
Copy-Item **/*.lib $BUN_DEPS_OUT_DIR

22
.build/boringssl.bash Normal file
View File

@@ -0,0 +1,22 @@
#!/usr/bin/env bash
set -euxo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
CMAKE_FLAGS=${CMAKE_FLAGS:-}
BUN_BASE_DIR=${BUN_BASE_DIR:-$(cd $SCRIPT_DIR && cd ../ && pwd)}
BUN_DEPS_OUT_DIR=${BUN_DEPS_OUT_DIR:-$BUN_BASE_DIR/src/deps/}
BUN_DEPS_DIR=${BUN_DEPS_DIR:-$BUN_BASE_DIR/src/deps}
CCACHE_CC_FLAG=${CCACHE_CC_FLAG:-}
CFLAGS=${CFLAGS:-}
mkdir -p $BUN_DEPS_OUT_DIR
cd $BUN_DEPS_DIR/boringssl
rm -rf build
mkdir -p build
cd build
CFLAGS="$CFLAGS" cmake $CMAKE_FLAGS -DCMAKE_EXE_LINKER_FLAGS="-fuse-ld=lld" -GNinja ..
ninja libcrypto.a libssl.a libdecrepit.a
cp **/libcrypto.a $BUN_DEPS_OUT_DIR/libcrypto.a
cp **/libssl.a $BUN_DEPS_OUT_DIR/libssl.a
cp **/libdecrepit.a $BUN_DEPS_OUT_DIR/libdecrepit.a

19
.build/boringssl.ps1 Normal file
View File

@@ -0,0 +1,19 @@
$ErrorActionPreference = 'Stop' # Setting strict mode, similar to 'set -euo pipefail' in bash
$SCRIPT_DIR = Split-Path $PSScriptRoot -Parent
$CMAKE_FLAGS = $env:CMAKE_FLAGS
$BUN_BASE_DIR = if ($env:BUN_BASE_DIR) { $env:BUN_BASE_DIR } else { $SCRIPT_DIR }
$BUN_DEPS_OUT_DIR = if ($env:BUN_DEPS_OUT_DIR) { $env:BUN_DEPS_OUT_DIR } else { Join-Path $BUN_BASE_DIR 'src\deps' }
$BUN_DEPS_DIR = if ($env:BUN_DEPS_DIR) { $env:BUN_DEPS_DIR } else { Join-Path $BUN_BASE_DIR 'src\deps' }
$CCACHE_CC_FLAG = $env:CCACHE_CC_FLAG
$CPUS = if ($env:CPUS) { $env:CPUS } else { (Get-WmiObject -Class Win32_ComputerSystem).NumberOfLogicalProcessors }
$CFLAGS = $env:CFLAGS
$CXXFLAGS = $env:CXXFLAGS
mkdir -p $BUN_DEPS_OUT_DIR -Force
Set-Location $BUN_DEPS_DIR/boringssl
cmake $CMAKE_FLAGS .
cmake --build . --target crypto --target ssl --target decrepit --clean-first --config Release
Copy-Item crypto/Release/crypto.lib $BUN_DEPS_OUT_DIR
Copy-Item ssl/Release/ssl.lib $BUN_DEPS_OUT_DIR
Copy-Item decrepit/Release/decrepit.lib $BUN_DEPS_OUT_DIR

24
.build/cares.ps1 Normal file
View File

@@ -0,0 +1,24 @@
$ErrorActionPreference = 'Stop' # Setting strict mode, similar to 'set -euo pipefail' in bash
$SCRIPT_DIR = Split-Path $PSScriptRoot -Parent
$CMAKE_FLAGS = $env:CMAKE_FLAGS
$BUN_BASE_DIR = if ($env:BUN_BASE_DIR) { $env:BUN_BASE_DIR } else { $SCRIPT_DIR }
$BUN_DEPS_OUT_DIR = if ($env:BUN_DEPS_OUT_DIR) { $env:BUN_DEPS_OUT_DIR } else { Join-Path $BUN_BASE_DIR 'src\deps' }
$BUN_DEPS_DIR = if ($env:BUN_DEPS_DIR) { $env:BUN_DEPS_DIR } else { Join-Path $BUN_BASE_DIR 'src\deps' }
$CCACHE_CC_FLAG = $env:CCACHE_CC_FLAG
$CPUS = if ($env:CPUS) { $env:CPUS } else { (Get-WmiObject -Class Win32_ComputerSystem).NumberOfLogicalProcessors }
$CFLAGS = $env:CFLAGS
$CXXFLAGS = $env:CXXFLAGS
# Create the output directory if it doesn't exist
if (-not (Test-Path $BUN_DEPS_OUT_DIR)) {
New-Item -ItemType Directory -Path $BUN_DEPS_OUT_DIR
}
Set-Location (Join-Path $BUN_DEPS_DIR 'c-ares')
rm -r build -ErrorAction SilentlyContinue
mkdir build -ErrorAction SilentlyContinue
cd build
cmake $CMAKE_FLAGS -DCMAKE_BUILD_TYPE=Release -G "Visual Studio 17 2022" -DCARES_STATIC=ON -DCARES_SHARED=OFF ..
cmake --build . --clean-first --config Release
cp ./lib/Release/*.lib $BUN_DEPS_OUT_DIR

22
.build/libarchive.bash Normal file
View File

@@ -0,0 +1,22 @@
#!/usr/bin/env bash
set -euxo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
CMAKE_FLAGS=${CMAKE_FLAGS:-}
BUN_BASE_DIR=${BUN_BASE_DIR:-$(cd $SCRIPT_DIR && cd ../ && pwd)}
BUN_DEPS_OUT_DIR=${BUN_DEPS_OUT_DIR:-$BUN_BASE_DIR/src/deps/}
BUN_DEPS_DIR=${BUN_DEPS_DIR:-$BUN_BASE_DIR/src/deps}
CCACHE_CC_FLAG=${CCACHE_CC_FLAG:-}
CPUS=${CPUS:-$(nproc || sysctl -n hw.ncpu || echo 1)}
CFLAGS=${CFLAGS:-}
mkdir -p $BUN_DEPS_OUT_DIR
cd $BUN_DEPS_DIR/libarchive
make clean || echo ""
./build/clean.sh || echo ""
./build/autogen.sh
CFLAGS="$CFLAGS" $CCACHE_CC_FLAG ./configure --disable-shared --enable-static --with-pic --disable-bsdtar --disable-bsdcat --disable-rpath --enable-posix-regex-lib --without-xml2 --without-expat --without-openssl --without-iconv --without-zlib
make -j$CPUS
cp ./.libs/libarchive.a $BUN_DEPS_OUT_DIR/libarchive.a

16
.build/libarchive.ps1 Normal file
View File

@@ -0,0 +1,16 @@
$ErrorActionPreference = 'Stop' # Setting strict mode, similar to 'set -euo pipefail' in bash
$SCRIPT_DIR = Split-Path $PSScriptRoot -Parent
$CMAKE_FLAGS = $env:CMAKE_FLAGS
$BUN_BASE_DIR = if ($env:BUN_BASE_DIR) { $env:BUN_BASE_DIR } else { $SCRIPT_DIR }
$BUN_DEPS_OUT_DIR = if ($env:BUN_DEPS_OUT_DIR) { $env:BUN_DEPS_OUT_DIR } else { Join-Path $BUN_BASE_DIR 'src\deps' }
$BUN_DEPS_DIR = if ($env:BUN_DEPS_DIR) { $env:BUN_DEPS_DIR } else { Join-Path $BUN_BASE_DIR 'src\deps' }
$CCACHE_CC_FLAG = $env:CCACHE_CC_FLAG
$CPUS = if ($env:CPUS) { $env:CPUS } else { (Get-WmiObject -Class Win32_ComputerSystem).NumberOfLogicalProcessors }
$CFLAGS = $env:CFLAGS
$CXXFLAGS = $env:CXXFLAGS
Set-Location $BUN_DEPS_DIR/libarchive
cmake -DBUILD_SHARED_LIBS=OFF -DENABLE_TEST=OFF -DENABLE_INSTALL=OFF --compile-no-warning-as-error $CMAKE_FLAGS .
cmake --build . --target ALL_BUILD --clean-first --config Release -- /p:WarningLevel=0
Copy-Item libarchive/Release/archive.lib $BUN_DEPS_OUT_DIR

16
.build/lolhtml.bash Normal file
View File

@@ -0,0 +1,16 @@
#!/usr/bin/env bash
set -euxo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
CMAKE_FLAGS=${CMAKE_FLAGS:-}
BUN_BASE_DIR=${BUN_BASE_DIR:-$(cd $SCRIPT_DIR && cd ../ && pwd)}
BUN_DEPS_OUT_DIR=${BUN_DEPS_OUT_DIR:-$BUN_BASE_DIR/src/deps/}
BUN_DEPS_DIR=${BUN_DEPS_DIR:-$BUN_BASE_DIR/src/deps}
CCACHE_CC_FLAG=${CCACHE_CC_FLAG:-}
CFLAGS=${CFLAGS:-}
mkdir -p $BUN_DEPS_OUT_DIR
cd $BUN_DEPS_DIR/lol-html/c-api
cargo build --release
cp target/release/liblolhtml.a $BUN_DEPS_OUT_DIR

16
.build/lolhtml.ps1 Normal file
View File

@@ -0,0 +1,16 @@
$ErrorActionPreference = 'Stop' # Setting strict mode, similar to 'set -euo pipefail' in bash
$SCRIPT_DIR = Split-Path $PSScriptRoot -Parent
$CMAKE_FLAGS = $env:CMAKE_FLAGS
$BUN_BASE_DIR = if ($env:BUN_BASE_DIR) { $env:BUN_BASE_DIR } else { $SCRIPT_DIR }
$BUN_DEPS_OUT_DIR = if ($env:BUN_DEPS_OUT_DIR) { $env:BUN_DEPS_OUT_DIR } else { Join-Path $BUN_BASE_DIR 'src\deps' }
$BUN_DEPS_DIR = if ($env:BUN_DEPS_DIR) { $env:BUN_DEPS_DIR } else { Join-Path $BUN_BASE_DIR 'src\deps' }
$CCACHE_CC_FLAG = $env:CCACHE_CC_FLAG
$CPUS = if ($env:CPUS) { $env:CPUS } else { (Get-WmiObject -Class Win32_ComputerSystem).NumberOfLogicalProcessors }
$CFLAGS = $env:CFLAGS
$CXXFLAGS = $env:CXXFLAGS
Set-Location $BUN_DEPS_DIR/lol-html/c-api
cargo build --release --target x86_64-pc-windows-msvc
Copy-Item target/x86_64-pc-windows-msvc/release/lolhtml.lib $BUN_DEPS_OUT_DIR
Copy-Item target/x86_64-pc-windows-msvc/release/lolhtml.pdb $BUN_DEPS_OUT_DIR

View File

@@ -0,0 +1,38 @@
#!/usr/bin/env bash
set -euxo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
CMAKE_FLAGS=${CMAKE_FLAGS:-}
BUN_BASE_DIR=${BUN_BASE_DIR:-$(cd $SCRIPT_DIR && cd ../ && pwd)}
BUN_DEPS_OUT_DIR=${BUN_DEPS_OUT_DIR:-$BUN_BASE_DIR/src/deps/}
BUN_DEPS_DIR=${BUN_DEPS_DIR:-$BUN_BASE_DIR/src/deps}
CCACHE_CC_FLAG=${CCACHE_CC_FLAG:-}
CPUS=${CPUS:-$(nproc || sysctl -n hw.ncpu || echo 1)}
CFLAGS=${CFLAGS:-}
MIMALLOC_OVERRIDE_FLAG=${MIMALLOC_OVERRIDE_FLAG:-}
MIMALLOC_VALGRIND_ENABLED_FLAG=${MIMALLOC_VALGRIND_ENABLED_FLAG:-}
mkdir -p $BUN_DEPS_OUT_DIR
rm -rf $(BUN_DEPS_DIR)/mimalloc/CMakeCache* $(BUN_DEPS_DIR)/mimalloc/CMakeFiles
cd $(BUN_DEPS_DIR)/mimalloc
make clean || echo ""
CFLAGS="$CFLAGS" cmake $CMAKE_FLAGS $MIMALLOC_OVERRIDE_FLAG $MIMALLOC_VALGRIND_ENABLED_FLAG \
-DCMAKE_BUILD_TYPE=Debug \
-DMI_DEBUG_FULL=1 \
-DMI_SKIP_COLLECT_ON_EXIT=1 \
-DMI_BUILD_SHARED=OFF \
-DMI_BUILD_STATIC=ON \
-DMI_BUILD_TESTS=OFF \
-DMI_OSX_ZONE=OFF \
-DMI_OSX_INTERPOSE=OFF \
-DMI_BUILD_OBJECT=ON \
-DMI_USE_CXX=ON \
-DMI_OVERRIDE=OFF \
-DCMAKE_C_FLAGS="$CFLAGS" \
-DCMAKE_CXX_FLAGS="$CFLAGS" \
-GNinja .
ninja
cp $BUN_DEPS_DIR/mimalloc/libmimalloc-debug.a $BUN_DEPS_OUT_DIR/libmimalloc.a

37
.build/mimalloc.bash Normal file
View File

@@ -0,0 +1,37 @@
#!/usr/bin/env bash
set -euxo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
CMAKE_FLAGS=${CMAKE_FLAGS:-}
BUN_BASE_DIR=${BUN_BASE_DIR:-$(cd $SCRIPT_DIR && cd ../ && pwd)}
BUN_DEPS_OUT_DIR=${BUN_DEPS_OUT_DIR:-$BUN_BASE_DIR/src/deps/}
BUN_DEPS_DIR=${BUN_DEPS_DIR:-$BUN_BASE_DIR/src/deps}
CCACHE_CC_FLAG=${CCACHE_CC_FLAG:-}
CPUS=${CPUS:-$(nproc || sysctl -n hw.ncpu || echo 1)}
CFLAGS=${CFLAGS:-}
MIMALLOC_OVERRIDE_FLAG=${MIMALLOC_OVERRIDE_FLAG:-}
MIMALLOC_VALGRIND_ENABLED_FLAG=${MIMALLOC_VALGRIND_ENABLED_FLAG:-}
mkdir -p $BUN_DEPS_OUT_DIR
rm -rf $BUN_DEPS_DIR/mimalloc/CMakeCache* $BUN_DEPS_DIR/mimalloc/CMakeFiles
cd $BUN_DEPS_DIR/mimalloc
make clean || echo ""
CFLAGS="$CFLAGS" cmake $CMAKE_FLAGS $MIMALLOC_OVERRIDE_FLAG \
-DMI_SKIP_COLLECT_ON_EXIT=1 \
-DMI_BUILD_SHARED=OFF \
-DMI_BUILD_STATIC=ON \
-DMI_BUILD_TESTS=OFF \
-DMI_OSX_ZONE=OFF \
-DMI_OSX_INTERPOSE=OFF \
-DMI_BUILD_OBJECT=ON \
-DMI_USE_CXX=ON \
-DMI_OVERRIDE=OFF \
-DMI_OSX_ZONE=OFF \
-DCMAKE_C_FLAGS="$CFLAGS" \
-GNinja .
ninja
cp $BUN_DEPS_DIR/mimalloc/libmimalloc.a $BUN_DEPS_OUT_DIR/libmimalloc.a

22
.build/mimalloc.ps1 Normal file
View File

@@ -0,0 +1,22 @@
$ErrorActionPreference = 'Stop' # Setting strict mode, similar to 'set -euo pipefail' in bash
$SCRIPT_DIR = Split-Path $PSScriptRoot -Parent
$CMAKE_FLAGS = $env:CMAKE_FLAGS
$BUN_BASE_DIR = if ($env:BUN_BASE_DIR) { $env:BUN_BASE_DIR } else { $SCRIPT_DIR }
$BUN_DEPS_OUT_DIR = if ($env:BUN_DEPS_OUT_DIR) { $env:BUN_DEPS_OUT_DIR } else { Join-Path $BUN_BASE_DIR 'src\deps' }
$BUN_DEPS_DIR = if ($env:BUN_DEPS_DIR) { $env:BUN_DEPS_DIR } else { Join-Path $BUN_BASE_DIR 'src\deps' }
$CCACHE_CC_FLAG = $env:CCACHE_CC_FLAG
$CPUS = if ($env:CPUS) { $env:CPUS } else { (Get-WmiObject -Class Win32_ComputerSystem).NumberOfLogicalProcessors }
$CFLAGS = $env:CFLAGS
$CXXFLAGS = $env:CXXFLAGS
# Create the output directory if it doesn't exist
if (-not (Test-Path $BUN_DEPS_OUT_DIR)) {
New-Item -ItemType Directory -Path $BUN_DEPS_OUT_DIR
}
Set-Location (Join-Path $BUN_DEPS_DIR 'mimalloc')
cmake $CMAKE_FLAGS -DMI_SKIP_COLLECT_ON_EXIT=1 -DMI_BUILD_SHARED=OFF -DMI_BUILD_STATIC=ON -DMI_BUILD_TESTS=OFF -DMI_OSX_ZONE=OFF -DMI_OSX_INTERPOSE=OFF -DMI_BUILD_OBJECT=ON -DMI_USE_CXX=ON -DMI_OVERRIDE=OFF -DMI_OSX_ZONE=OFF -DCMAKE_C_FLAGS="$CFLAGS" .
cmake --build . --clean-first --config Release
Copy-Item **/*.lib $BUN_DEPS_OUT_DIR

22
.build/tinycc.bash Normal file
View File

@@ -0,0 +1,22 @@
#!/usr/bin/env bash
set -euxo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
CMAKE_FLAGS=${CMAKE_FLAGS:-}
BUN_BASE_DIR=${BUN_BASE_DIR:-$(cd $SCRIPT_DIR && cd ../ && pwd)}
BUN_DEPS_OUT_DIR=${BUN_DEPS_OUT_DIR:-$BUN_BASE_DIR/src/deps/}
BUN_DEPS_DIR=${BUN_DEPS_DIR:-$BUN_BASE_DIR/src/deps}
CCACHE_CC_FLAG=${CCACHE_CC_FLAG:-}
CPUS=${CPUS:-$(nproc || sysctl -n hw.ncpu || echo 1)}
AR=${AR:-ar}
CC=${CC:-cc}
CFLAGS=${CFLAGS:-}
mkdir -p $BUN_DEPS_OUT_DIR
cd $BUN_DEPS_DIR/tinycc
make clean
AR=$AR CC=$CC CFLAGS="$CFLAGS" ./configure --enable-static --cc=$CC --ar=$AR --config-predefs=yes
make -j10
cp *.a $BUN_DEPS_OUT_DIR

18
.build/zlib.bash Normal file
View File

@@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -euxo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
CMAKE_FLAGS=${CMAKE_FLAGS:-}
BUN_BASE_DIR=${BUN_BASE_DIR:-$(cd $SCRIPT_DIR && cd ../ && pwd)}
BUN_DEPS_OUT_DIR=${BUN_DEPS_OUT_DIR:-$BUN_BASE_DIR/src/deps/}
BUN_DEPS_DIR=${BUN_DEPS_DIR:-$BUN_BASE_DIR/src/deps}
CCACHE_CC_FLAG=${CCACHE_CC_FLAG:-}
CPUS=${CPUS:-$(nproc || sysctl -n hw.ncpu || echo 1)}
mkdir -p $BUN_DEPS_OUT_DIR
cd $BUN_DEPS_DIR/zlib
make clean
$CCACHE_CC_FLAG CFLAGS="$CFLAGS" ./configure --static
make -j${CPUS}
cp ./libz.a $BUN_DEPS_OUT_DIR/libz.a

19
.build/zstd.bash Normal file
View File

@@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euxo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)
CMAKE_FLAGS=${CMAKE_FLAGS:-}
BUN_BASE_DIR=${BUN_BASE_DIR:-$(cd $SCRIPT_DIR && cd ../ && pwd)}
BUN_DEPS_OUT_DIR=${BUN_DEPS_OUT_DIR:-$BUN_BASE_DIR/src/deps/}
BUN_DEPS_DIR=${BUN_DEPS_DIR:-$BUN_BASE_DIR/src/deps}
CCACHE_CC_FLAG=${CCACHE_CC_FLAG:-}
CPUS=${CPUS:-$(nproc || sysctl -n hw.ncpu || echo 1)}
mkdir -p $BUN_DEPS_OUT_DIR
cd $BUN_DEPS_DIR/zstd
rm -rf Release CMakeCache.txt CMakeFiles
cmake $CMAKE_FLAGS -DZSTD_BUILD_STATIC=ON -B Release -S build/cmake -G Ninja
ninja -C Release
cp Release/lib/libzstd.a $BUN_DEPS_OUT_DIR/libzstd.a

21
.build/zstd.ps1 Normal file
View File

@@ -0,0 +1,21 @@
$ErrorActionPreference = 'Stop' # Setting strict mode, similar to 'set -euo pipefail' in bash
$SCRIPT_DIR = Split-Path $PSScriptRoot -Parent
$CMAKE_FLAGS = $env:CMAKE_FLAGS
$BUN_BASE_DIR = if ($env:BUN_BASE_DIR) { $env:BUN_BASE_DIR } else { $SCRIPT_DIR }
$BUN_DEPS_OUT_DIR = if ($env:BUN_DEPS_OUT_DIR) { $env:BUN_DEPS_OUT_DIR } else { Join-Path $BUN_BASE_DIR 'src\deps' }
$BUN_DEPS_DIR = if ($env:BUN_DEPS_DIR) { $env:BUN_DEPS_DIR } else { Join-Path $BUN_BASE_DIR 'src\deps' }
$CCACHE_CC_FLAG = $env:CCACHE_CC_FLAG
$CPUS = if ($env:CPUS) { $env:CPUS } else { (Get-WmiObject -Class Win32_ComputerSystem).NumberOfLogicalProcessors }
$CFLAGS = $env:CFLAGS
$CXXFLAGS = $env:CXXFLAGS
# Create the output directory if it doesn't exist
if (-not (Test-Path $BUN_DEPS_OUT_DIR)) {
New-Item -ItemType Directory -Path $BUN_DEPS_OUT_DIR
}
Set-Location (Join-Path $BUN_DEPS_DIR 'zstd\build\cmake')
cmake $CMAKE_FLAGS -DZSTD_BUILD_STATIC=ON -DCMAKE_BUILD_TYPE=Release
cmake --build . --clean-first --config Release
Copy-Item lib\*\**.lib $BUN_DEPS_OUT_DIR

16
.gitignore vendored
View File

@@ -132,4 +132,18 @@ src/js/out/DebugPath.h
make-dev-stats.csv
.uuid
tsconfig.tsbuildinfo
tsconfig.tsbuildinfo
CMakeFiles
build.ninja
.ninja_deps
.ninja_log
CMakeCache.txt
cmake_install.cmake
compile_commands.json
*.lib
x64
**/*.vcxproj*
**/*.sln*
**/*.dir
**/*.pdb

8
.vscode/launch.json generated vendored
View File

@@ -123,7 +123,7 @@
"type": "lldb",
"request": "launch",
"name": "bun run [file]",
"program": "bun-debug",
"program": "./Build/debug/bun.exe",
"args": ["run", "${file}", "${file}"],
"cwd": "${fileDirname}",
"env": {
@@ -307,11 +307,9 @@
"name": "bun install",
"program": "bun-debug",
"args": ["install"],
"cwd": "${fileDirname}",
"cwd": "/Users/jarred/Build/worky",
"console": "internalConsole",
"env": {
"BUN_DEBUG_QUIET_LOGS": "1"
}
"env": {}
},
{

60
.vscode/settings.json vendored
View File

@@ -27,6 +27,7 @@
"editor.formatOnSave": true
},
"zig.zls.enableInlayHints": false,
"zig.zls.enabled": true,
"[jsx]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
@@ -66,7 +67,7 @@
"**/*.xcodeproj": true,
"test/snapshots": true,
"test/snapshots-no-hmr": true,
"src/bun.js/WebKit": true,
"WebKit": true,
"src/deps/libarchive": true,
"src/deps/mimalloc": true,
"src/deps/s2n-tls": true,
@@ -80,25 +81,27 @@
"src/deps/zstd": true,
"test/snippets/package-json-exports/_node_modules_copy": true,
"src/js/out": true,
"src/packages/bun-uws/fuzzing/seed-corpus/": true
"src/bun.js/WebKit": true,
"**/*.dir": true,
"packages/bun-uws/fuzzing/seed-corpus/": true
},
"C_Cpp.files.exclude": {
"**/.vscode": true,
"src/bun.js/WebKit/JSTests": true,
"src/bun.js/WebKit/Tools": true,
"src/bun.js/WebKit/WebDriverTests": true,
"src/bun.js/WebKit/WebKit.xcworkspace": true,
"src/bun.js/WebKit/WebKitLibraries": true,
"src/bun.js/WebKit/Websites": true,
"src/bun.js/WebKit/resources": true,
"src/bun.js/WebKit/LayoutTests": true,
"src/bun.js/WebKit/ManualTests": true,
"src/bun.js/WebKit/PerformanceTests": true,
"src/bun.js/WebKit/WebKitLegacy": true,
"src/bun.js/WebKit/WebCore": true,
"src/bun.js/WebKit/WebDriver": true,
"src/bun.js/WebKit/WebKitBuild": true,
"src/bun.js/WebKit/WebInspectorUI": true
"WebKit/JSTests": true,
"WebKit/Tools": true,
"WebKit/WebDriverTests": true,
"WebKit/WebKit.xcworkspace": true,
"WebKit/WebKitLibraries": true,
"WebKit/Websites": true,
"WebKit/resources": true,
"WebKit/LayoutTests": true,
"WebKit/ManualTests": true,
"WebKit/PerformanceTests": true,
"WebKit/WebKitLegacy": true,
"WebKit/WebCore": true,
"WebKit/WebDriver": true,
"WebKit/WebKitBuild": true,
"WebKit/WebInspectorUI": true
},
"[cpp]": {
"editor.defaultFormatter": "xaver.clang-format"
@@ -218,7 +221,28 @@
"regex": "cpp",
"span": "cpp",
"valarray": "cpp",
"codecvt": "cpp"
"codecvt": "cpp",
"types.h": "c",
"bsd.h": "c",
"xtr1common": "cpp",
"stop_token": "cpp",
"xfacet": "cpp",
"xhash": "cpp",
"xiosbase": "cpp",
"xlocale": "cpp",
"xlocbuf": "cpp",
"xlocinfo": "cpp",
"xlocmes": "cpp",
"xlocmon": "cpp",
"xlocnum": "cpp",
"xloctime": "cpp",
"xmemory": "cpp",
"xstring": "cpp",
"xtree": "cpp",
"xutility": "cpp",
"string.h": "c",
"zutil.h": "c",
"gzguts.h": "c"
},
"cmake.configureOnOpen": false,
"C_Cpp.errorSquiggles": "enabled",

516
CMakeLists.txt Normal file
View File

@@ -0,0 +1,516 @@
cmake_minimum_required(VERSION 3.25)
cmake_policy(SET CMP0091 NEW)
project(bun)
set(DEFAULT_USE_STATIC_SQLITE ON)
if(APPLE)
set(DEFAULT_USE_STATIC_SQLITE OFF)
endif()
set(DEFAULT_ZIG_EXECUTABLE "zig")
if (DEFINED ENV{ZIG})
set(DEFAULT_ZIG_EXECUTABLE $ENV{ZIG})
endif()
set(DEFAULT_BUN_EXECUTABLE "bun")
if (DEFINED ENV{BUN})
set(DEFAULT_BUN_EXECUTABLE $ENV{BUN})
endif()
set(DEFAULT_CPU_TARGET "native")
add_compile_definitions("JSC_OBJC_API_ENABLED=0")
if (ARCH STREQUAL "x86_64")
if (NOT MSVC)
if (USE_BASELINE_BUILD)
set(DEFAULT_CPU_TARGET "nehalem")
else ()
set(DEFAULT_CPU_TARGET "haswell")
endif()
endif()
endif()
# Check for environment variable
if (DEFINED ENV{CPU_TARGET})
set(DEFAULT_CPU_TARGET $ENV{CPU_TARGET})
endif()
set(DEFAULT_CUSTOM_UNLESS_WINDOWS ON)
if (WIN32)
set(DEFAULT_CUSTOM_UNLESS_WINDOWS OFF)
endif()
option(USE_STATIC_SQLITE "Statically link SQLite?" DEFAULT_USE_STATIC_SQLITE)
option(USE_CUSTOM_ZLIB "Use Bun's recommended version of zlib" DEFAULT_CUSTOM_UNLESS_WINDOWS)
option(USE_CUSTOM_BORINGSSL "Use Bun's recommended version of BoringSSL" ON)
option(USE_CUSTOM_LIBARCHIVE "Use Bun's recommended version of libarchive" ON)
option(USE_CUSTOM_MIMALLOC "Use Bun's recommended version of Mimalloc" ON)
option(USE_CUSTOM_ZSTD "Use Bun's recommended version of zstd`" ON)
option(USE_CUSTOM_CARES "Use Bun's recommended version of c-ares" DEFAULT_CUSTOM_UNLESS_WINDOWS)
option(USE_CUSTOM_BASE64 "Use Bun's recommended version of libbase64" ON)
option(USE_CUSTOM_LOLHTML "Use Bun's recommended version of lolhtml" ON)
option(USE_CUSTOM_TINYCC "Use Bun's recommended version of tinycc" ON)
option(USE_CUSTOM_LIBUV "Use Bun's recommended version of libuv (Windows only)" OFF)
option(USE_BASELINE_BUILD "Build Bun for older CPUs" OFF)
set(ZIG_EXECUTABLE "${DEFAULT_ZIG_EXECUTABLE}" CACHE STRING "Path to zig executable")
set(BUN_EXECUTABLE "${DEFAULT_BUN_EXECUTABLE}" CACHE STRING "Path to bun executable")
set(WEBKIT_LIB_DIR "${CMAKE_CURRENT_SOURCE_DIR}/bun-webkit/lib" CACHE STRING "WebKit lib folder")
set(WEBKIT_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/bun-webkit/include" CACHE STRING "WebKit include folder")
set(BUN_DEPS_DIR "${CMAKE_CURRENT_SOURCE_DIR}/src/deps" CACHE STRING "Directory holding submodules" )
set(BUN_LIB_DIR "${CMAKE_CURRENT_SOURCE_DIR}/src/deps" CACHE STRING "Directory holding static libraries" )
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_C_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(HOMEBREW_PREFIX /usr/local)
set(ARCH x86_64)
set(LINUX OFF)
if(UNIX AND NOT APPLE)
set(LINUX ON)
endif()
add_compile_definitions("BUILDING_JSCONLY__")
add_definitions(-D_HAS_EXCEPTIONS=0)
find_program(CCACHE_PROGRAM ccache)
if(CCACHE_PROGRAM)
set(CMAKE_CXX_COMPILER_LAUNCHER "${CCACHE_PROGRAM}")
set(CMAKE_C_COMPILER_LAUNCHER "${CCACHE_PROGRAM}")
message(STATUS "Using ccache")
endif()
file(GLOB bun_SRC
"${CMAKE_CURRENT_SOURCE_DIR}/src/deps/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/io/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/bun.js/modules/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/bun.js/bindings/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/bun.js/bindings/WebCore/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/bun.js/bindings/sqlite/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/bun.js/bindings/webcrypto/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/bun.js/bindings/webcrypto/*/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/js/out/*.cpp"
"${CMAKE_CURRENT_SOURCE_DIR}/src/deps/picohttpparser/picohttpparser.c"
)
file(GLOB uSockets_FILES
"${CMAKE_CURRENT_SOURCE_DIR}/packages/bun-usockets/src/*.c"
"${CMAKE_CURRENT_SOURCE_DIR}/packages/bun-usockets/src/eventing/*.c"
"${CMAKE_CURRENT_SOURCE_DIR}/packages/bun-usockets/src/internal/*.c"
"${CMAKE_CURRENT_SOURCE_DIR}/packages/bun-usockets/src/crypto/*.c"
"${CMAKE_CURRENT_SOURCE_DIR}/packages/bun-usockets/src/crypto/*.cpp"
)
add_compile_definitions(
"LIBUS_USE_OPENSSL=1"
"UWS_HTTPRESPONSE_NO_WRITEMARK=1"
"LIBUS_USE_BORINGSSL=1"
"WITH_BORINGSSL=1"
)
include_directories(
packages/bun-uws
packages
packages/bun-usockets
packages/bun-usockets/src
src/bun.js/bindings
src/bun.js/bindings/webcore
src/bun.js/bindings/webcrypto
src/bun.js/bindings/sqlite
src/bun.js/modules
src/js/out
src/js/out/modules
src/js/builtins
src/napi
src/deps
src/deps/picohttpparser
)
add_compile_definitions(
"STATICALLY_LINKED_WITH_JavaScriptCore=1"
"STATICALLY_LINKED_WITH_WTF=1"
"STATICALLY_LINKED_WITH_BMALLOC=1"
"BUILDING_WITH_CMAKE=1"
"BUN_SINGLE_THREADED_PER_VM_ENTRY_SCOPE=1"
"NAPI_EXPERIMENTAL=ON"
"NDEBUG=1"
"NOMINMAX"
"IS_BUILD"
"BUILDING_JSCONLY__"
"ASSERT_ENABLED=0"
)
# If arm64
if (CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64" OR CMAKE_SYSTEM_PROCESSOR MATCHES "arm64" OR CMAKE_SYSTEM_PROCESSOR MATCHES "arm")
set(ARCH arm64)
endif()
if (ARCH STREQUAL "arm64" AND APPLE)
set(HOMEBREW_PREFIX /opt/homebrew)
endif()
set(BUN_OBJECT_FILE zig-out/lib/bun.o)
if (CMAKE_BUILD_TYPE STREQUAL "Debug")
set(BUN_OBJECT_FILE zig-out/lib/bun-debug.o)
if (NOT MSVC)
string(APPEND CMAKE_CXX_FLAGS " -g3 -O1")
string(APPEND CMAKE_C_FLAGS " -g3 -O1")
else()
string(APPEND CMAKE_CXX_FLAGS " /O1 ")
string(APPEND CMAKE_C_FLAGS " /O1 ")
endif()
add_compile_definitions("BUN_DEBUG")
elseif (NOT MSVC)
string(APPEND CMAKE_CXX_FLAGS " -O3 -femit-llvm " )
string(APPEND CMAKE_C_FLAGS " -O3 -femit-llvm ")
else ()
string(APPEND CMAKE_CXX_FLAGS " /O2 " )
string(APPEND CMAKE_C_FLAGS " /O2 ")
endif()
set(EXTRA_SRC "")
if (WIN32)
set(EXTRA_SRC "${CMAKE_CURRENT_SOURCE_DIR}/src/bun.js/bindings/musl-memmem.c")
add_compile_definitions("WIN32")
add_compile_definitions("_WINDOWS")
add_compile_definitions("_CRT_SECURE_NO_WARNINGS")
add_compile_definitions("WIN32_LEAN_AND_MEAN=1")
endif()
# if clang
if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
string(APPEND CMAKE_CXX_FLAGS " -fconstexpr-steps=1271242 -fconstexpr-depth=27 ")
string(APPEND CMAKE_CXX_FLAGS
"-fno-exceptions "
"-fno-rtti "
"-ferror-limit=100 "
"-fvisibility=hidden "
"-fvisibility-inlines-hidden "
)
string(APPEND CMAKE_C_FLAGS
"-ferror-limit=100 "
"-fvisibility=hidden "
"-fvisibility-inlines-hidden "
)
elseif(MSVC)
string(APPEND SUPPRESS_WARNING_NUMBERS
# JSC deletes operator delete to prevent accidental use
"/wd4291 "
# we use #pragma mark in some places
"/wd4068 "
)
string(APPEND CMAKE_CXX_FLAGS " /EHsc /GR- ")
string(APPEND CMAKE_C_FLAGS " /EHsc /GR- /MP ${SUPPRESS_WARNING_NUMBERS} /experimental:c11atomics /std:c17 ")
string(APPEND CMAKE_CXX_FLAGS " /Zc:__cplusplus /Zc:inline /bigobj /MP ${SUPPRESS_WARNING_NUMBERS} ")
endif()
if (APPLE)
string(APPEND CMAKE_LINKER_FLAGS " -fno-keep-static-consts -Wl,-dead_strip -Wl,-dead_strip_dylibs ")
string(APPEND CMAKE_CXX_FLAGS " -stdlib=libc++")
string(APPEND CMAKE_CXX_FLAGS " -mmacosx-version-min=11")
string(APPEND CMAKE_C_FLAGS " -mmacosx-version-min=11")
endif()
SET(CPU_TARGET "${DEFAULT_CPU_TARGET}" CACHE STRING "CPU target")
if (NOT MSVC)
string(APPEND CMAKE_CXX_FLAGS " -march=${CPU_TARGET} -mtune=${CPU_TARGET} ")
string(APPEND CMAKE_C_FLAGS " -march=${CPU_TARGET} -mtune=${CPU_TARGET} ")
else()
# string(APPEND CMAKE_CXX_FLAGS " /arch:x64 ")
# string(APPEND CMAKE_C_FLAGS " /arch:x64 ")
endif()
file(GLOB ZIG_FILES
"src/*.zig"
"src/*/*.zig"
"src/*/*/*.zig"
"src/*/*/*/*.zig"
"src/*/*/*/*/*.zig")
set(IDENTIFIER_CACHE_FILES
"${CMAKE_CURRENT_SOURCE_DIR}/src/js_lexer/id_continue_bitset.blob"
"${CMAKE_CURRENT_SOURCE_DIR}/src/js_lexer/id_continue_bitset.meta.blob"
"${CMAKE_CURRENT_SOURCE_DIR}/src/js_lexer/id_start_bitset.blob"
"${CMAKE_CURRENT_SOURCE_DIR}/src/js_lexer/id_start_bitset.meta.blob")
add_custom_command(
OUTPUT ${BUN_OBJECT_FILE}
COMMAND "${ZIG_EXECUTABLE}" build obj -Doptimize=${CMAKE_BUILD_TYPE} -Doutput-dir=${CMAKE_CURRENT_SOURCE_DIR}/zig-out/lib -Dcpu=${CPU_TARGET} -Dtarget=x86_64-windows-msvc
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/build.zig ${ZIG_FILES}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
COMMENT "Building zig code"
VERBATIM
)
# add_custom_command(
# TARGET bun
# COMMAND bun ./codegen/index.ts
# DEPENDS src/js/modules/**/*.{js,ts}
# COMMENT "Running bun codegen"
# )
add_executable(bun WIN32 ${bun_SRC} ${uSockets_FILES} ${BUN_OBJECT_FILE} ${EXTRA_SRC})
# Set /subsystem:console on bun for windows
if (WIN32)
set_target_properties(bun PROPERTIES LINK_FLAGS " /SUBSYSTEM:CONSOLE ")
endif()
set_target_properties(bun PROPERTIES
CXX_STANDARD 20
CXX_STANDARD_REQUIRED YES
CXX_EXTENSIONS YES
CXX_VISIBILITY_PRESET hidden
C_STANDARD 17
C_STANDARD_REQUIRED YES
VISIBILITY_INLINES_HIDDEN YES
)
set(CMAKE_COLOR_DIAGNOSTICS ON)
if (APPLE)
target_link_libraries(bun PRIVATE "${HOMEBREW_PREFIX}/opt/libiconv/lib/libiconv.a")
target_link_libraries(bun PRIVATE "resolv")
target_link_libraries(bun PRIVATE "stdc++")
target_link_libraries(bun PRIVATE "${HOMEBREW_PREFIX}/opt/icu4c/lib/libicudata.a")
target_link_libraries(bun PRIVATE "${HOMEBREW_PREFIX}/opt/icu4c/lib/libicui18n.a")
target_link_libraries(bun PRIVATE "${HOMEBREW_PREFIX}/opt/icu4c/lib/libicuuc.a")
target_link_libraries(bun PRIVATE "icucore")
elseif (LINUX)
string(APPEND CMAKE_CXX_FLAGS " -static-libstdc++ -static-libgcc -fno-omit-frame-pointer")
string(APPEND CMAKE_C_FLAGS " -static-libgcc -fno-omit-frame-pointer")
target_link_libraries(bun PRIVATE "c")
string(APPEND CMAKE_LINKER_FLAGS
" -Wl,--compress-debug-sections=zlib "
" -l:libatomic.a "
" -Wl,-Bsymbolics-functions "
" -fno-semantic-interposition "
" -Wl,-z,now"
" -Wl,--as-needed"
" -Wl,--gc-sections"
" -Wl,-z,-stack-size=12800000"
" -Wl,--wrap=fcntl"
" -Wl,--wrap=fcntl64"
" -Wl,--wrap=stat64"
" -Wl,--wrap=pow"
" -Wl,--wrap=exp"
" -Wl,--wrap=log"
" -Wl,--wrap=log2"
" -Wl,--wrap=lstat"
" -Wl,--wrap=stat"
" -Wl,--wrap=fstat"
" -Wl,--wrap=fstatat"
" -Wl,--wrap=lstat64"
" -Wl,--wrap=stat64"
" -Wl,--wrap=fstat64"
" -Wl,--wrap=fstatat64"
" -Wl,--wrap=mknod"
" -Wl,--wrap=mknodat"
" -Wl,--wrap=statx "
)
endif()
if (USE_CUSTOM_ZLIB AND (NOT WIN32))
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/libz.a")
include_directories(${BUN_DEPS_DIR}/zlib/include)
else ()
find_package(ZLIB REQUIRED)
target_link_libraries(bun PRIVATE ZLIB::ZLIB)
endif ()
if (USE_CUSTOM_BORINGSSL)
include_directories(src/deps/boringssl/include)
if (WIN32)
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/crypto.lib")
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/ssl.lib")
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/decrepit.lib")
else()
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/libcrypto.a")
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/libssl.a")
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/libdecrepit.a")
endif()
else ()
include(FindBoringSSL)
FindBoringSSL(bun)
endif()
if (USE_CUSTOM_LIBARCHIVE)
include_directories(src/deps/libarchive/include)
if (WIN32)
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/archive.lib")
else()
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/libarchive.a")
endif()
else ()
find_package(LibArchive REQUIRED)
target_link_libraries(bun PRIVATE LibArchive::LibArchive)
endif()
if (USE_CUSTOM_MIMALLOC)
include_directories(src/deps/mimalloc/include)
if (WIN32)
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/mimalloc-static.lib")
else()
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/libmimalloc.a")
endif()
else ()
find_package(mimalloc REQUIRED)
target_link_libraries(bun PRIVATE mimalloc)
endif()
if (USE_CUSTOM_ZSTD)
include_directories(src/deps/zstd/include)
if (WIN32)
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/zstd.lib")
else()
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/libzstd.a")
endif()
else ()
find_package(zstd CONFIG REQUIRED)
target_link_libraries(bun PRIVATE zstd::libzstd)
endif()
if (USE_CUSTOM_CARES)
include_directories(src/deps/zstd/include)
if (WIN32)
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/cares.lib")
else()
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/libcares.a")
endif()
else ()
find_package(c-ares CONFIG REQUIRED)
target_link_libraries(bun PRIVATE c-ares::cares)
endif()
if (USE_CUSTOM_BASE64)
include_directories(src/deps/base64/include)
if (WIN32)
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/base64.lib")
else()
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/libbase64.a")
endif()
else ()
find_package(base64 REQUIRED)
target_link_libraries(bun PRIVATE base64::base64)
endif()
if (NOT WIN32)
if (USE_CUSTOM_TINYCC)
if (WIN32)
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/tcc.lib")
else()
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/libtcc.a")
endif()
else ()
find_package(tinycc REQUIRED)
target_link_libraries(bun PRIVATE tinycc::tinycc)
endif()
endif()
set_property(TARGET bun PROPERTY
MSVC_RUNTIME_LIBRARY "MultiThreadedDLL"
)
if (USE_CUSTOM_LOLHTML)
if (WIN32)
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/lolhtml.lib")
else()
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/liblolhtml.a")
endif()
else ()
find_package(lolhtml REQUIRED)
target_link_libraries(bun PRIVATE lolhtml::lolhtml)
endif()
if (WIN32)
if (USE_CUSTOM_LIBUV)
target_link_libraries(bun PRIVATE "${BUN_LIB_DIR}/uv.lib")
else ()
find_package(libuv CONFIG REQUIRED )
target_link_libraries(bun PRIVATE $<IF:$<TARGET_EXISTS:libuv::uv_a>,libuv::uv_a,libuv::uv>)
endif()
endif()
if (USE_STATIC_SQLITE)
add_library(sqlite3 STATIC src/bun.js/bindings/sqlite/sqlite3.c)
target_include_directories(sqlite3 PUBLIC src/bun.js/bindings/sqlite)
target_link_libraries(bun PRIVATE sqlite3)
target_compile_definitions(bun PRIVATE "LAZY_LOAD_SQLITE=0")
else()
target_compile_definitions(bun PRIVATE "LAZY_LOAD_SQLITE=1")
endif()
if (NOT MSVC)
string(APPEND CMAKE_CXX_FLAGS " -fPIC ")
endif()
if (NOT MSVC)
target_link_libraries(bun PRIVATE "${WEBKIT_LIB_DIR}/libWTF.a")
target_link_libraries(bun PRIVATE "${WEBKIT_LIB_DIR}/libJavaScriptCore.a")
target_link_libraries(bun PRIVATE "${WEBKIT_LIB_DIR}/libbmalloc.a")
else()
target_link_libraries(bun PRIVATE "${WEBKIT_LIB_DIR}/WTF.lib")
target_link_libraries(bun PRIVATE "${WEBKIT_LIB_DIR}/JavaScriptCore.lib")
if (WIN32)
string (APPEND CMAKE_CXX_FLAGS
" /external:anglebrackets /Gs- /Zi "
)
string (APPEND CMAKE_FLAGS
" /external:anglebrackets /Gs- /Zi "
)
set_target_properties(bun PROPERTIES LINK_FLAGS " /SUBSYSTEM:CONSOLE /STACK:4194304,2097152 ")
endif()
if (DEFINED ENV{VCPKG_ROOT})
include_directories($ENV{VCPKG_ROOT}/installed/x64-windows/include)
endif()
# include_directories(C:/Users/windo/Build/WebKit/WebKitBuild/WTF/DerivedSources)
# include_directories(C:/Users/windo/Build/WebKit/WebKitBuild/WTF/Headers)
file(COPY C:/Users/windo/Code/WebKit/WebKitBuild/cmakeconfig.h DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/src/bun.js/bindings)
include_directories(C:/Users/windo/Code/WebKit/WebKitLibraries/win/include)
link_directories(C:/Users/windo/Code/WebKit/WebKitLibraries/win/lib64)
target_link_directories(bun PUBLIC ${ICU_LIBRARY})
target_link_libraries(bun PUBLIC icuuc icudt icutu icuio icuin icutest)
target_link_libraries(bun PUBLIC winmm ws2_32 bcrypt ntdll kernel32 shell32 shlwapi advapi32 vcruntime ucrt legacy_stdio_definitions)
endif()

View File

@@ -22,7 +22,7 @@ ARG ZIG_URL="https://ziglang.org/builds/${ZIG_FILENAME}"
ARG GIT_SHA=""
ARG BUN_BASE_VERSION=1.0
FROM bitnami/minideb:bullseye as bun-base
FROM bitnami/minideb:bookworm as bun-base
RUN install_packages ca-certificates curl wget lsb-release software-properties-common gnupg gnupg1 gnupg2

View File

@@ -38,7 +38,11 @@ NATIVE_OR_OLD_MARCH = -march=nehalem
endif
MIN_MACOS_VERSION ?= $(DEFAULT_MIN_MACOS_VERSION)
<<<<<<< HEAD
BUN_BASE_VERSION = 0.9
=======
BUN_BASE_VERSION = 1.0
>>>>>>> main
CI ?= false
@@ -66,7 +70,7 @@ PACKAGE_JSON_VERSION = $(BUN_BASE_VERSION).$(BUILD_ID)
BUN_BUILD_TAG = bun-v$(PACKAGE_JSON_VERSION)
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")
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_RELEASE_DIR ?= $(WEBKIT_DIR)/WebKitBuild/Release
@@ -74,7 +78,7 @@ WEBKIT_DEBUG_DIR ?= $(WEBKIT_DIR)/WebKitBuild/Debug
WEBKIT_RELEASE_DIR_LTO ?= $(WEBKIT_DIR)/WebKitBuild/ReleaseLTO
NPM_CLIENT ?= $(shell which bun 2>/dev/null || which npm 2>/dev/null)
NPM_CLIENT = "$(shell which bun 2>/dev/null || which npm 2>/dev/null)"
ZIG ?= $(shell which zig 2>/dev/null || echo -e "error: Missing zig. Please make sure zig is in PATH. Or set ZIG=/path/to-zig-executable")
# We must use the same compiler version for the JavaScriptCore bindings and JavaScriptCore
@@ -764,7 +768,7 @@ USOCKETS_DIR = $(BUN_DIR)/packages/bun-usockets
USOCKETS_SRC_DIR = $(USOCKETS_DIR)/src
usockets:
rm -rf $(USOCKETS_DIR)/*.i $(USOCKETS_DIR)/*.bc $(USOCKETS_DIR)/*.o $(USOCKETS_DIR)/*.s $(USOCKETS_DIR)/*.ii $(USOCKETS_DIR)/*.s
rm -rf $(USOCKETS_DIR)/*.i $(USOCKETS_DIR)/*.bc $(USOCKETS_DIR)/*.o $(USOCKETS_DIR)/*.s $(USOCKETS_DIR)/*.ii $(USOCKETS_DIR)/*.s $(BUN_DEPS_OUT_DIR)/libusockets.a
cd $(USOCKETS_DIR) && $(CC_WITH_CCACHE) -I$(USOCKETS_SRC_DIR) -fno-builtin-malloc -fno-builtin-free -fno-builtin-realloc $(EMIT_LLVM_FOR_RELEASE) $(MACOS_MIN_FLAG) -fPIC $(CFLAGS) $(UWS_CC_FLAGS) -save-temps -I$(BUN_DEPS_DIR)/uws/uSockets/src $(UWS_LDFLAGS) -g $(DEFAULT_LINKER_FLAGS) $(PLATFORM_LINKER_FLAGS) $(OPTIMIZATION_LEVEL) -c $(wildcard $(USOCKETS_SRC_DIR)/*.c) $(wildcard $(USOCKETS_SRC_DIR)/**/*.c)
cd $(USOCKETS_DIR) && $(CXX_WITH_CCACHE) -I$(USOCKETS_SRC_DIR) -fno-builtin-malloc -fno-builtin-free -fno-builtin-realloc $(EMIT_LLVM_FOR_RELEASE) $(MACOS_MIN_FLAG) -fPIC $(CXXFLAGS) $(UWS_CXX_FLAGS) -save-temps -I$(BUN_DEPS_DIR)/uws/uSockets/src $(UWS_LDFLAGS) -g $(DEFAULT_LINKER_FLAGS) $(PLATFORM_LINKER_FLAGS) $(OPTIMIZATION_LEVEL) -c $(wildcard $(USOCKETS_SRC_DIR)/*.cpp) $(wildcard $(USOCKETS_SRC_DIR)/**/*.cpp)
cd $(USOCKETS_DIR) && $(AR) rcvs $(BUN_DEPS_OUT_DIR)/libusockets.a $(USOCKETS_DIR)/*.{o,bc}

View File

@@ -6,23 +6,30 @@ bench("await 1", async function () {
return await 1;
});
function callnextTick(resolve) {
process.nextTick(resolve);
}
if (typeof process !== "undefined") {
bench("process.nextTick x 100", async function () {
var remaining = 100;
var cb, promise;
promise = new Promise(resolve => {
cb = resolve;
});
function awaitNextTick() {
return new Promise(callnextTick);
}
for (let i = 0; i < 100; i++) {
process.nextTick(() => {
if (--remaining === 0) cb();
});
}
bench("promise.nextTick", async function () {
return awaitNextTick();
});
return promise;
});
bench("await 1 x 100", async function () {
for (let i = 0; i < 100; i++) await 1;
});
}
bench("await new Promise(resolve => resolve())", async function () {
await new Promise(resolve => resolve());
});
bench("Promise.all(Array.from({length: 100}, () => new Promise((resolve) => resolve())))", async function () {
return Promise.all(Array.from({ length: 100 }, () => Promise.resolve(1)));
});
await run();

View File

@@ -11,6 +11,11 @@ fn moduleSource(comptime out: []const u8) FileSource {
}
}
fn exists(path: []const u8) bool {
_ = std.fs.openFileAbsolute(path, .{ .mode = .read_only }) catch return false;
return true;
}
const color_map = std.ComptimeStringMap([]const u8, .{
&.{ "black", "30m" },
&.{ "blue", "34m" },
@@ -46,6 +51,35 @@ fn addInternalPackages(b: *Build, step: *CompileStep, _: std.mem.Allocator, _: [
};
step.addModule("async_io", io);
step.addModule("zlib-internal", brk: {
if (target.isWindows()) {
break :brk b.createModule(.{
.source_file = FileSource.relative("src/deps/zlib.win32.zig")
});
}
break :brk b.createModule(.{
.source_file = FileSource.relative("src/deps/zlib.posix.zig")
});
});
var async_: *Module = brk: {
if (target.isDarwin() or target.isLinux() or target.isFreeBSD()) {
break :brk b.createModule(.{
.source_file = FileSource.relative("src/async/posix_event_loop.zig"),
});
} else if (target.isWindows()) {
break :brk b.createModule(.{
.source_file = FileSource.relative("src/async/windows_event_loop.zig"),
});
}
break :brk b.createModule(.{
.source_file = FileSource.relative("src/async/stub_event_loop.zig"),
});
};
step.addModule("async", async_);
}
const BunBuildOptions = struct {
@@ -59,6 +93,8 @@ const BunBuildOptions = struct {
runtime_js_version: u64 = 0,
fallback_html_version: u64 = 0,
tinycc: bool = true,
pub fn updateRuntime(this: *BunBuildOptions) anyerror!void {
if (std.fs.cwd().openFile("src/runtime.out.js", .{ .mode = .read_only })) |file| {
defer file.close();
@@ -97,6 +133,7 @@ const BunBuildOptions = struct {
opts.addOption(@TypeOf(this.base_path), "base_path", this.base_path);
opts.addOption(@TypeOf(this.runtime_js_version), "runtime_js_version", this.runtime_js_version);
opts.addOption(@TypeOf(this.fallback_html_version), "fallback_html_version", this.fallback_html_version);
opts.addOption(@TypeOf(this.tinycc), "tinycc", this.tinycc);
return opts;
}
};
@@ -150,7 +187,11 @@ pub fn build_(b: *Build) !void {
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
var target = b.standardTargetOptions(.{});
var target = b.standardTargetOptions(.{
.default_target = .{
// .os_tag = .windows,
},
});
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
optimize = b.standardOptimizeOption(.{});
@@ -187,7 +228,7 @@ pub fn build_(b: *Build) !void {
var triplet = triplet_buf[0 .. osname.len + cpuArchName.len + 1];
if (b.option([]const u8, "output-dir", "target to install to") orelse std.os.getenv("OUTPUT_DIR")) |output_dir_| {
if (b.option([]const u8, "output-dir", "target to install to") orelse b.env_map.get("OUTPUT_DIR")) |output_dir_| {
output_dir = try pathRel(b.allocator, b.install_prefix, output_dir_);
} else {
const output_dir_base = try std.fmt.bufPrint(&output_dir_buf, "{s}{s}", .{ bin_label, triplet });
@@ -220,6 +261,21 @@ pub fn build_(b: *Build) !void {
.main_pkg_path = .{ .cwd_relative = b.pathFromRoot(".") },
});
if (!exists(b.pathFromRoot(try std.fs.path.join(b.allocator, &.{
"src",
"js_lexer",
"id_continue_bitset.blob",
})))) {
const identifier_data = b.pathFromRoot(try std.fs.path.join(b.allocator, &.{ "src", "js_lexer", "identifier_data.zig" }));
var run_step = b.addSystemCommand(&.{
b.zig_exe,
"run",
identifier_data,
});
run_step.has_side_effects = true;
obj.step.dependOn(&run_step.step);
}
b.reference_trace = 16;
var default_build_options: BunBuildOptions = brk: {
@@ -246,7 +302,7 @@ pub fn build_(b: *Build) !void {
}
}
const is_canary = (std.os.getenvZ("BUN_CANARY") orelse "0")[0] == '1';
const is_canary = (b.env_map.get("BUN_CANARY") orelse "0")[0] == '1';
break :brk .{
.canary = is_canary,
.sha = git_sha,
@@ -304,12 +360,12 @@ pub fn build_(b: *Build) !void {
obj.addOptions("build_options", actual_build_options.step(b));
obj.linkLibC();
obj.dll_export_fns = true;
obj.strip = false;
obj.bundle_compiler_rt = false;
obj.omit_frame_pointer = optimize != .Debug;
obj.subsystem = .Console;
// Disable stack probing on x86 so we don't need to include compiler_rt
if (target.getCpuArch().isX86()) obj.disable_stack_probing = true;
if (target.getCpuArch().isX86() or target.isWindows()) obj.disable_stack_probing = true;
if (b.option(bool, "for-editor", "Do not emit bin, just check for errors") orelse false) {
// obj.emit_bin = .no_emit;

View File

@@ -27,7 +27,7 @@ pub fn main() anyerror!void {
var args = std.mem.bytesAsSlice([]u8, try std.process.argsAlloc(allocator));
const to_resolve = args[args.len - 1];
const cwd = try std.process.getCwdAlloc(allocator);
const cwd = try bun.getcwdAlloc(allocator);
var path: []u8 = undefined;
var out_buffer: [bun.MAX_PATH_BYTES]u8 = undefined;

View File

@@ -47,7 +47,7 @@ pub fn main() anyerror!void {
bun.asByteSlice(args[args.len - 1]),
};
const tarball_path = path_handler.joinAbsStringBuf(try std.process.getCwdAlloc(std.heap.c_allocator), &tarball_path_buf, &parts, .auto);
const tarball_path = path_handler.joinAbsStringBuf(try bun.getcwdAlloc(std.heap.c_allocator), &tarball_path_buf, &parts, .auto);
Output.prettyErrorln("Tarball Path: {s}", .{tarball_path});
var folder = basename;

View File

@@ -565,10 +565,10 @@ void *us_socket_context_ext(int ssl, struct us_socket_context_t *context) {
}
void us_socket_context_on_handshake(int ssl, struct us_socket_context_t *context, void (*on_handshake)(struct us_socket_context_t *, int success, struct us_bun_verify_error_t verify_error, void* custom_data), void* custom_data) {
void us_socket_context_on_handshake(int ssl, struct us_socket_context_t *context, void (*on_handshake)(struct us_socket_t *, int success, struct us_bun_verify_error_t verify_error, void* custom_data), void* custom_data) {
#ifndef LIBUS_NO_SSL
if (ssl) {
us_internal_on_ssl_handshake((struct us_internal_ssl_socket_context_t *) context, on_handshake, custom_data);
us_internal_on_ssl_handshake((struct us_internal_ssl_socket_context_t *) context, (us_internal_on_handshake_t)on_handshake, custom_data);
return;
}
#endif

View File

@@ -43,12 +43,9 @@ void *sni_find(void *sni, const char *hostname);
#include <wolfssl/openssl/dh.h>
#endif
#include "./root_certs.h"
#include <stdatomic.h>
static const root_certs_size = sizeof(root_certs) / sizeof(root_certs[0]);
static X509* root_cert_instances[root_certs_size] = {NULL};
static atomic_flag root_cert_instances_lock = ATOMIC_FLAG_INIT;
static atomic_bool root_cert_instances_initialized = 0;
/* These are in root_certs.cpp */
extern X509_STORE* us_get_default_ca_store();
struct loop_ssl_data {
char *ssl_read_input, *ssl_read_output;
@@ -86,7 +83,7 @@ struct us_internal_ssl_socket_context_t {
/* Pointer to sni tree, created when the context is created and freed likewise when freed */
void *sni;
void (*on_handshake)(struct us_internal_ssl_socket_t *, int success, struct us_bun_verify_error_t verify_error, void* custom_data);
us_internal_on_handshake_t on_handshake;
void* handshake_data;
};
@@ -202,7 +199,7 @@ void us_internal_on_ssl_handshake(struct us_internal_ssl_socket_context_t * cont
context->handshake_data = custom_data;
}
void us_internal_ssl_handshake(struct us_internal_ssl_socket_t *s, void (*on_handshake)(struct us_internal_ssl_socket_t *, int success, struct us_bun_verify_error_t verify_error, void* custom_data), void* custom_data) {
void us_internal_ssl_handshake(struct us_internal_ssl_socket_t *s, us_internal_on_handshake_t on_handshake, void* custom_data) {
struct us_internal_ssl_socket_context_t *context = (struct us_internal_ssl_socket_context_t *) us_socket_context(0, &s->s);
// will start on_open, on_writable or on_data
@@ -295,7 +292,7 @@ struct us_internal_ssl_socket_t *ssl_on_close(struct us_internal_ssl_socket_t *s
}
struct us_internal_ssl_socket_t *ssl_on_end(struct us_internal_ssl_socket_t *s) {
if(&s->s && s->pending_handshake) {
if (s && s->pending_handshake) {
s->pending_handshake = 0;
}
// whatever state we are in, a TCP FIN is always an answered shutdown
@@ -575,91 +572,6 @@ void free_ssl_context(SSL_CTX *ssl_context) {
SSL_CTX_free(ssl_context);
}
// This callback is used to avoid the default passphrase callback in OpenSSL
// which will typically prompt for the passphrase. The prompting is designed
// for the OpenSSL CLI, but works poorly for this case because it involves
// synchronous interaction with the controlling terminal, something we never
// want, and use this function to avoid it.
int us_no_password_callback(char* buf, int size, int rwflag, void* u) {
return 0;
}
static X509 * us_ssl_ctx_get_X509_without_callback_from(struct us_cert_string_t content) {
X509 *x = NULL;
BIO *in;
ERR_clear_error(); // clear error stack for SSL_CTX_use_certificate()
in = BIO_new_mem_buf(content.str, content.len);
if (in == NULL) {
OPENSSL_PUT_ERROR(SSL, ERR_R_BUF_LIB);
goto end;
}
x = PEM_read_bio_X509(in, NULL, us_no_password_callback, NULL);
if (x == NULL) {
OPENSSL_PUT_ERROR(SSL, ERR_R_PEM_LIB);
goto end;
}
return x;
end:
X509_free(x);
BIO_free(in);
return NULL;
}
int us_internal_raw_root_certs(struct us_cert_string_t** out) {
*out = root_certs;
return root_certs_size;
}
void us_internal_init_root_certs() {
if(atomic_load(&root_cert_instances_initialized) == 1) return;
while(atomic_flag_test_and_set_explicit(&root_cert_instances_lock, memory_order_acquire));
// if some thread already created it after we acquired the lock we skip and release the lock
if(atomic_load(&root_cert_instances_initialized) == 0) {
for (size_t i = 0; i < root_certs_size; i++) {
root_cert_instances[i] = us_ssl_ctx_get_X509_without_callback_from(root_certs[i]);
}
atomic_store(&root_cert_instances_initialized, 1);
}
atomic_flag_clear_explicit(&root_cert_instances_lock, memory_order_release);
}
X509_STORE* us_get_default_ca_store() {
X509_STORE *store = X509_STORE_new();
if (store == NULL) {
return NULL;
}
if (!X509_STORE_set_default_paths(store)) {
X509_STORE_free(store);
return NULL;
}
us_internal_init_root_certs();
// load all root_cert_instances on the default ca store
for (size_t i = 0; i < root_certs_size; i++) {
X509* cert = root_cert_instances[i];
if(cert == NULL) continue;
X509_up_ref(cert);
X509_STORE_add_cert(store, cert);
}
return store;
}
/* This function should take any options and return SSL_CTX - which has to be free'd with
* our destructor function - free_ssl_context() */
SSL_CTX *create_ssl_context_from_options(struct us_socket_context_options_t options) {

View File

@@ -0,0 +1,90 @@
// MSVC doesn't support C11 stdatomic.h propertly yet.
// so we use C++ std::atomic instead.
#include "./internal/internal.h"
#include "./root_certs.h"
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <atomic>
static const int root_certs_size = sizeof(root_certs) / sizeof(root_certs[0]);
static X509* root_cert_instances[sizeof(root_certs) / sizeof(root_certs[0])] = {NULL};
static std::atomic_flag root_cert_instances_lock = ATOMIC_FLAG_INIT;
static std::atomic_bool root_cert_instances_initialized = 0;
// This callback is used to avoid the default passphrase callback in OpenSSL
// which will typically prompt for the passphrase. The prompting is designed
// for the OpenSSL CLI, but works poorly for this case because it involves
// synchronous interaction with the controlling terminal, something we never
// want, and use this function to avoid it.
int us_no_password_callback(char* buf, int size, int rwflag, void* u) {
return 0;
}
static X509 * us_ssl_ctx_get_X509_without_callback_from(struct us_cert_string_t content) {
X509 *x = NULL;
BIO *in;
ERR_clear_error(); // clear error stack for SSL_CTX_use_certificate()
in = BIO_new_mem_buf(content.str, content.len);
if (in == NULL) {
OPENSSL_PUT_ERROR(SSL, ERR_R_BUF_LIB);
goto end;
}
x = PEM_read_bio_X509(in, NULL, us_no_password_callback, NULL);
if (x == NULL) {
OPENSSL_PUT_ERROR(SSL, ERR_R_PEM_LIB);
goto end;
}
return x;
end:
X509_free(x);
BIO_free(in);
return NULL;
}
static void us_internal_init_root_certs() {
if(std::atomic_load(&root_cert_instances_initialized) == 1) return;
while(atomic_flag_test_and_set_explicit(&root_cert_instances_lock, std::memory_order_acquire));
if(!atomic_exchange(&root_cert_instances_initialized, 1)) {
for (size_t i = 0; i < root_certs_size; i++) {
root_cert_instances[i] = us_ssl_ctx_get_X509_without_callback_from(root_certs[i]);
}
}
atomic_flag_clear_explicit(&root_cert_instances_lock, std::memory_order_release);
}
extern "C" int us_internal_raw_root_certs(struct us_cert_string_t** out) {
*out = root_certs;
return root_certs_size;
}
extern "C" X509_STORE* us_get_default_ca_store() {
X509_STORE *store = X509_STORE_new();
if (store == NULL) {
return NULL;
}
if (!X509_STORE_set_default_paths(store)) {
X509_STORE_free(store);
return NULL;
}
us_internal_init_root_certs();
// load all root_cert_instances on the default ca store
for (size_t i = 0; i < root_certs_size; i++) {
X509* cert = root_cert_instances[i];
if(cert == NULL) continue;
X509_up_ref(cert);
X509_STORE_add_cert(store, cert);
}
return store;
}

View File

@@ -35,8 +35,8 @@ void us_loop_run_bun_tick(struct us_loop_t *loop, int64_t timeoutMs);
/* Pointer tags are used to indicate a Bun pointer versus a uSockets pointer */
#define UNSET_BITS_49_UNTIL_64 0x0000FFFFFFFFFFFF
#define CLEAR_POINTER_TAG(p) ((void *) ((uintptr_t) (p) & UNSET_BITS_49_UNTIL_64))
#define LIKELY(cond) __builtin_expect((uint64_t)(void*)cond, 1)
#define UNLIKELY(cond) __builtin_expect((uint64_t)(void*)cond, 0)
#define LIKELY(cond) __builtin_expect((_Bool)(cond), 1)
#define UNLIKELY(cond) __builtin_expect((_Bool)(cond), 0)
#ifdef LIBUS_USE_EPOLL
#define GET_READY_POLL(loop, index) (struct us_poll_t *) loop->ready_polls[index].data.ptr

View File

@@ -0,0 +1,330 @@
/*
* Authored by Alex Hultman, 2018-2021.
* Intellectual property of third-party.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "internal/internal.h"
#include "libusockets.h"
#include <stdlib.h>
#ifdef LIBUS_USE_LIBUV
/* uv_poll_t->data always (except for most times after calling us_poll_stop)
* points to the us_poll_t */
static void poll_cb(uv_poll_t *p, int status, int events) {
us_internal_dispatch_ready_poll((struct us_poll_t *)p->data, status < 0,
events);
}
static void prepare_cb(uv_prepare_t *p) {
struct us_loop_t *loop = p->data;
us_internal_loop_pre(loop);
}
/* Note: libuv timers execute AFTER the post callback */
static void check_cb(uv_check_t *p) {
struct us_loop_t *loop = p->data;
us_internal_loop_post(loop);
}
/* Not used for polls, since polls need two frees */
static void close_cb_free(uv_handle_t *h) { free(h->data); }
/* This one is different for polls, since we need two frees here */
static void close_cb_free_poll(uv_handle_t *h) {
/* It is only in case we called us_poll_stop then quickly us_poll_free that we
* enter this. Most of the time, actual freeing is done by us_poll_free. */
if (h->data) {
free(h->data);
free(h);
}
}
static void timer_cb(uv_timer_t *t) {
struct us_internal_callback_t *cb = t->data;
cb->cb(cb);
}
static void async_cb(uv_async_t *a) {
struct us_internal_callback_t *cb = a->data;
// internal asyncs give their loop, not themselves
cb->cb((struct us_internal_callback_t *)cb->loop);
}
// poll
void us_poll_init(struct us_poll_t *p, LIBUS_SOCKET_DESCRIPTOR fd,
int poll_type) {
p->poll_type = poll_type;
p->fd = fd;
}
void us_poll_free(struct us_poll_t *p, struct us_loop_t *loop) {
/* The idea here is like so; in us_poll_stop we call uv_close after setting
* data of uv-poll to 0. This means that in close_cb_free we call free on 0
* with does nothing, since us_poll_stop should not really free the poll.
* HOWEVER, if we then call us_poll_free while still closing the uv-poll, we
* simply change back the data to point to our structure so that we actually
* do free it like we should. */
if (uv_is_closing((uv_handle_t *)p->uv_p)) {
p->uv_p->data = p;
} else {
free(p->uv_p);
free(p);
}
}
void us_poll_start(struct us_poll_t *p, struct us_loop_t *loop, int events) {
p->poll_type = us_internal_poll_type(p) |
((events & LIBUS_SOCKET_READABLE) ? POLL_TYPE_POLLING_IN : 0) |
((events & LIBUS_SOCKET_WRITABLE) ? POLL_TYPE_POLLING_OUT : 0);
uv_poll_init_socket(loop->uv_loop, p->uv_p, p->fd);
uv_poll_start(p->uv_p, events, poll_cb);
}
void us_poll_change(struct us_poll_t *p, struct us_loop_t *loop, int events) {
if (us_poll_events(p) != events) {
p->poll_type =
us_internal_poll_type(p) |
((events & LIBUS_SOCKET_READABLE) ? POLL_TYPE_POLLING_IN : 0) |
((events & LIBUS_SOCKET_WRITABLE) ? POLL_TYPE_POLLING_OUT : 0);
uv_poll_start(p->uv_p, events, poll_cb);
}
}
void us_poll_stop(struct us_poll_t *p, struct us_loop_t *loop) {
uv_poll_stop(p->uv_p);
/* We normally only want to close the poll here, not free it. But if we stop
* it, then quickly "free" it with us_poll_free, we postpone the actual
* freeing to close_cb_free_poll whenever it triggers. That's why we set data
* to null here, so that us_poll_free can reset it if needed */
p->uv_p->data = 0;
uv_close((uv_handle_t *)p->uv_p, close_cb_free_poll);
}
int us_poll_events(struct us_poll_t *p) {
return ((p->poll_type & POLL_TYPE_POLLING_IN) ? LIBUS_SOCKET_READABLE : 0) |
((p->poll_type & POLL_TYPE_POLLING_OUT) ? LIBUS_SOCKET_WRITABLE : 0);
}
unsigned int us_internal_accept_poll_event(struct us_poll_t *p) { return 0; }
int us_internal_poll_type(struct us_poll_t *p) { return p->poll_type & 3; }
void us_internal_poll_set_type(struct us_poll_t *p, int poll_type) {
p->poll_type = poll_type | (p->poll_type & 12);
}
LIBUS_SOCKET_DESCRIPTOR us_poll_fd(struct us_poll_t *p) { return p->fd; }
void us_loop_pump(struct us_loop_t *loop) {
uv_run(loop->uv_loop, UV_RUN_NOWAIT);
}
struct us_loop_t *us_create_loop(void *hint,
void (*wakeup_cb)(struct us_loop_t *loop),
void (*pre_cb)(struct us_loop_t *loop),
void (*post_cb)(struct us_loop_t *loop),
unsigned int ext_size) {
struct us_loop_t *loop =
(struct us_loop_t *)malloc(sizeof(struct us_loop_t) + ext_size);
loop->uv_loop = hint ? hint : uv_loop_new();
loop->is_default = hint != 0;
loop->uv_pre = malloc(sizeof(uv_prepare_t));
uv_prepare_init(loop->uv_loop, loop->uv_pre);
uv_prepare_start(loop->uv_pre, prepare_cb);
uv_unref((uv_handle_t *)loop->uv_pre);
loop->uv_pre->data = loop;
loop->uv_check = malloc(sizeof(uv_check_t));
uv_check_init(loop->uv_loop, loop->uv_check);
uv_unref((uv_handle_t *)loop->uv_check);
uv_check_start(loop->uv_check, check_cb);
loop->uv_check->data = loop;
// here we create two unreffed handles - timer and async
us_internal_loop_data_init(loop, wakeup_cb, pre_cb, post_cb);
// if we do not own this loop, we need to integrate and set up timer
if (hint) {
us_loop_integrate(loop);
}
return loop;
}
// based on if this was default loop or not
void us_loop_free(struct us_loop_t *loop) {
// ref and close down prepare and check
uv_ref((uv_handle_t *)loop->uv_pre);
uv_prepare_stop(loop->uv_pre);
loop->uv_pre->data = loop->uv_pre;
uv_close((uv_handle_t *)loop->uv_pre, close_cb_free);
uv_ref((uv_handle_t *)loop->uv_check);
uv_check_stop(loop->uv_check);
loop->uv_check->data = loop->uv_check;
uv_close((uv_handle_t *)loop->uv_check, close_cb_free);
us_internal_loop_data_free(loop);
// we need to run the loop one last round to call all close callbacks
// we cannot do this if we do not own the loop, default
if (!loop->is_default) {
uv_run(loop->uv_loop, UV_RUN_NOWAIT);
uv_loop_delete(loop->uv_loop);
}
// now we can free our part
free(loop);
}
void us_loop_run(struct us_loop_t *loop) {
us_loop_integrate(loop);
uv_run(loop->uv_loop, UV_RUN_NOWAIT);
}
struct us_poll_t *us_create_poll(struct us_loop_t *loop, int fallthrough,
unsigned int ext_size) {
struct us_poll_t *p =
(struct us_poll_t *)malloc(sizeof(struct us_poll_t) + ext_size);
p->uv_p = malloc(sizeof(uv_poll_t));
p->uv_p->data = p;
return p;
}
/* If we update our block position we have to updarte the uv_poll data to point
* to us */
struct us_poll_t *us_poll_resize(struct us_poll_t *p, struct us_loop_t *loop,
unsigned int ext_size) {
struct us_poll_t *new_p = realloc(p, sizeof(struct us_poll_t) + ext_size);
new_p->uv_p->data = new_p;
return new_p;
}
// timer
struct us_timer_t *us_create_timer(struct us_loop_t *loop, int fallthrough,
unsigned int ext_size) {
struct us_internal_callback_t *cb = malloc(
sizeof(struct us_internal_callback_t) + sizeof(uv_timer_t) + ext_size);
cb->loop = loop;
cb->cb_expects_the_loop = 0; // never read?
cb->leave_poll_ready = 0; // never read?
uv_timer_t *uv_timer = (uv_timer_t *)(cb + 1);
uv_timer_init(loop->uv_loop, uv_timer);
uv_timer->data = cb;
if (fallthrough) {
uv_unref((uv_handle_t *)uv_timer);
}
return (struct us_timer_t *)cb;
}
void *us_timer_ext(struct us_timer_t *timer) {
return ((char *)timer) + sizeof(struct us_internal_callback_t) +
sizeof(uv_timer_t);
}
void us_timer_close(struct us_timer_t *t) {
struct us_internal_callback_t *cb = (struct us_internal_callback_t *)t;
uv_timer_t *uv_timer = (uv_timer_t *)(cb + 1);
// always ref the timer before closing it
uv_ref((uv_handle_t *)uv_timer);
uv_timer_stop(uv_timer);
uv_timer->data = cb;
uv_close((uv_handle_t *)uv_timer, close_cb_free);
}
void us_timer_set(struct us_timer_t *t, void (*cb)(struct us_timer_t *t),
int ms, int repeat_ms) {
struct us_internal_callback_t *internal_cb =
(struct us_internal_callback_t *)t;
internal_cb->cb = (void (*)(struct us_internal_callback_t *))cb;
uv_timer_t *uv_timer = (uv_timer_t *)(internal_cb + 1);
if (!ms) {
uv_timer_stop(uv_timer);
} else {
uv_timer_start(uv_timer, timer_cb, ms, repeat_ms);
}
}
struct us_loop_t *us_timer_loop(struct us_timer_t *t) {
struct us_internal_callback_t *internal_cb =
(struct us_internal_callback_t *)t;
return internal_cb->loop;
}
// async (internal only)
struct us_internal_async *us_internal_create_async(struct us_loop_t *loop,
int fallthrough,
unsigned int ext_size) {
struct us_internal_callback_t *cb = malloc(
sizeof(struct us_internal_callback_t) + sizeof(uv_async_t) + ext_size);
cb->loop = loop;
return (struct us_internal_async *)cb;
}
void us_internal_async_close(struct us_internal_async *a) {
struct us_internal_callback_t *cb = (struct us_internal_callback_t *)a;
uv_async_t *uv_async = (uv_async_t *)(cb + 1);
// always ref the async before closing it
uv_ref((uv_handle_t *)uv_async);
uv_async->data = cb;
uv_close((uv_handle_t *)uv_async, close_cb_free);
}
void us_internal_async_set(struct us_internal_async *a,
void (*cb)(struct us_internal_async *)) {
struct us_internal_callback_t *internal_cb =
(struct us_internal_callback_t *)a;
internal_cb->cb = (void (*)(struct us_internal_callback_t *))cb;
uv_async_t *uv_async = (uv_async_t *)(internal_cb + 1);
uv_async_init(internal_cb->loop->uv_loop, uv_async, async_cb);
uv_unref((uv_handle_t *)uv_async);
uv_async->data = internal_cb;
}
void us_internal_async_wakeup(struct us_internal_async *a) {
struct us_internal_callback_t *internal_cb =
(struct us_internal_callback_t *)a;
uv_async_t *uv_async = (uv_async_t *)(internal_cb + 1);
uv_async_send(uv_async);
}
#endif

View File

@@ -0,0 +1,47 @@
/*
* Authored by Alex Hultman, 2018-2019.
* Intellectual property of third-party.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LIBUV_H
#define LIBUV_H
#include "internal/loop_data.h"
#include <uv.h>
#define LIBUS_SOCKET_READABLE UV_READABLE
#define LIBUS_SOCKET_WRITABLE UV_WRITABLE
struct us_loop_t {
alignas(LIBUS_EXT_ALIGNMENT) struct us_internal_loop_data_t data;
uv_loop_t *uv_loop;
int is_default;
uv_prepare_t *uv_pre;
uv_check_t *uv_check;
};
// it is no longer valid to cast a pointer to us_poll_t to a pointer of
// uv_poll_t
struct us_poll_t {
/* We need to hold a pointer to this uv_poll_t since we need to be able to
* resize our block */
uv_poll_t *uv_p;
LIBUS_SOCKET_DESCRIPTOR fd;
unsigned char poll_type;
};
#endif // LIBUV_H

View File

@@ -20,7 +20,9 @@
#if defined(_MSC_VER)
#ifndef __cplusplus
#define alignas(x) __declspec(align(x))
#endif
#else
#include <stdalign.h>
#endif
@@ -43,6 +45,10 @@ void us_internal_loop_update_pending_ready_polls(struct us_loop_t *loop, struct
#include "internal/eventing/epoll_kqueue.h"
#endif
#ifdef LIBUS_USE_LIBUV
#include "internal/eventing/libuv.h"
#endif
/* Poll type and what it polls for */
enum {
/* Two first bits */
@@ -126,6 +132,15 @@ struct us_internal_callback_t {
#endif
#if __cplusplus
extern "C" {
#endif
int us_internal_raw_root_certs(struct us_cert_string_t** out);
#if __cplusplus
}
#endif
/* Listen sockets are sockets */
struct us_listen_socket_t {
alignas(LIBUS_EXT_ALIGNMENT) struct us_socket_t s;
@@ -163,6 +178,7 @@ struct us_socket_context_t {
struct us_internal_ssl_socket_context_t;
struct us_internal_ssl_socket_t;
typedef void (*us_internal_on_handshake_t)(struct us_internal_ssl_socket_t *, int success, struct us_bun_verify_error_t verify_error, void* custom_data);
/* SNI functions */
void us_internal_ssl_socket_context_add_server_name(struct us_internal_ssl_socket_context_t *context, const char *hostname_pattern, struct us_socket_context_options_t options, void *user);
@@ -190,8 +206,8 @@ void us_internal_ssl_socket_context_on_close(struct us_internal_ssl_socket_conte
void us_internal_ssl_socket_context_on_data(struct us_internal_ssl_socket_context_t *context,
struct us_internal_ssl_socket_t *(*on_data)(struct us_internal_ssl_socket_t *s, char *data, int length));
void us_internal_ssl_handshake(struct us_internal_ssl_socket_t *s, void (*on_handshake)(struct us_internal_ssl_socket_t *, int success, struct us_bun_verify_error_t verify_error, void* custom_data), void* custom_data);
void us_internal_on_ssl_handshake(struct us_internal_ssl_socket_context_t * context, void (*on_handshake)(struct us_internal_ssl_socket_t *, int success, struct us_bun_verify_error_t verify_error, void* custom_data), void* custom_data);
void us_internal_ssl_handshake(struct us_internal_ssl_socket_t *s, us_internal_on_handshake_t on_handshake, void* custom_data);
void us_internal_on_ssl_handshake(struct us_internal_ssl_socket_context_t * context, us_internal_on_handshake_t on_handshake, void* custom_data);
void us_internal_ssl_socket_context_on_writable(struct us_internal_ssl_socket_context_t *context,
struct us_internal_ssl_socket_t *(*on_writable)(struct us_internal_ssl_socket_t *s));

View File

@@ -153,6 +153,12 @@ struct us_socket_context_options_t {
int ssl_prefer_low_memory_usage; /* Todo: rename to prefer_low_memory_usage and apply for TCP as well */
};
struct us_bun_verify_error_t {
long error;
const char* code;
const char* reason;
};
struct us_socket_events_t {
struct us_socket_t *(*on_open)(struct us_socket_t *, int is_client, char *ip, int ip_length);
struct us_socket_t *(*on_data)(struct us_socket_t *, char *data, int length);
@@ -166,11 +172,6 @@ struct us_socket_events_t {
void (*on_handshake)(struct us_socket_t*, int success, struct us_bun_verify_error_t verify_error, void* custom_data);
};
struct us_bun_verify_error_t {
long error;
const char* code;
const char* reason;
};
struct us_bun_socket_context_options_t {
const char *key_file_name;
@@ -231,7 +232,7 @@ void us_socket_context_on_long_timeout(int ssl, struct us_socket_context_t *cont
void us_socket_context_on_connect_error(int ssl, struct us_socket_context_t *context,
struct us_socket_t *(*on_connect_error)(struct us_socket_t *s, int code));
void us_socket_context_on_handshake(int ssl, struct us_socket_context_t *context, void (*on_handshake)(struct us_socket_context_t *, int success, struct us_bun_verify_error_t verify_error, void* custom_data), void* custom_data);
void us_socket_context_on_handshake(int ssl, struct us_socket_context_t *context, void (*on_handshake)(struct us_socket_t *, int success, struct us_bun_verify_error_t verify_error, void* custom_data), void* custom_data);
/* Emitted when a socket has been half-closed */
void us_socket_context_on_end(int ssl, struct us_socket_context_t *context, struct us_socket_t *(*on_end)(struct us_socket_t *s));

View File

@@ -18,7 +18,9 @@
#include "libusockets.h"
#include "internal/internal.h"
#include <stdlib.h>
#ifndef WIN32
#include <sys/ioctl.h>
#endif
/* The loop has 2 fallthrough polls */
void us_internal_loop_data_init(struct us_loop_t *loop, void (*wakeup_cb)(struct us_loop_t *loop),

View File

@@ -156,7 +156,7 @@ struct us_socket_t *us_socket_detach(int ssl, struct us_socket_t *s) {
s->next = 0;
s->low_prio_state = 0;
} else {
us_internal_socket_context_unlink(s->context, s);
us_internal_socket_context_unlink_socket(s->context, s);
}
us_poll_stop((struct us_poll_t *) s, s->context->loop);
@@ -186,7 +186,7 @@ struct us_socket_t *us_socket_attach(int ssl, LIBUS_SOCKET_DESCRIPTOR client_fd,
/* We always use nodelay */
bsd_socket_nodelay(client_fd, 1);
us_internal_socket_context_link(ctx, s);
us_internal_socket_context_link_socket(ctx, s);
if (ctx->on_open) ctx->on_open(s, 0, 0, 0);

View File

@@ -206,9 +206,9 @@ public:
unsigned char *b = (unsigned char *) binary.data();
if (binary.length() == 4) {
ipLength = sprintf(buf, "%u.%u.%u.%u", b[0], b[1], b[2], b[3]);
ipLength = snprintf(buf, sizeof(buf), "%u.%u.%u.%u", b[0], b[1], b[2], b[3]);
} else {
ipLength = sprintf(buf, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
ipLength = snprintf(buf, sizeof(buf), "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11],
b[12], b[13], b[14], b[15]);
}

View File

@@ -79,7 +79,7 @@ pub fn setThreadName(name: StringTypes.stringZ) void {
/// Flushes stdout and stderr and exits with the given code.
pub fn exit(code: u8) noreturn {
Output.flush();
std.os.exit(code);
std.c._exit(code);
}
pub const AllocatorConfiguration = struct {

View File

@@ -0,0 +1,843 @@
const bun = @import("root").bun;
const Output = bun.Output;
const JSC = bun.JSC;
const uws = bun.uws;
const Environment = bun.Environment;
const std = @import("std");
pub const Loop = uws.Loop;
/// Track if an object whose file descriptor is being watched should keep the event loop alive.
/// This is not reference counted. It only tracks active or inactive.
pub const KeepAlive = struct {
status: Status = .inactive,
const log = Output.scoped(.KeepAlive, false);
const Status = enum { active, inactive, done };
pub inline fn isActive(this: KeepAlive) bool {
return this.status == .active;
}
/// Make calling ref() on this poll into a no-op.
pub fn disable(this: *KeepAlive) void {
this.unref(JSC.VirtualMachine.get());
this.status = .done;
}
/// Only intended to be used from EventLoop.Pollable
pub fn deactivate(this: *KeepAlive, loop: *Loop) void {
if (this.status != .active)
return;
this.status = .inactive;
loop.num_polls -= 1;
loop.active -|= 1;
}
/// Only intended to be used from EventLoop.Pollable
pub fn activate(this: *KeepAlive, loop: *Loop) void {
if (this.status != .inactive)
return;
this.status = .active;
loop.num_polls += 1;
loop.active += 1;
}
pub fn init() KeepAlive {
return .{};
}
/// Prevent a poll from keeping the process alive.
pub fn unref(this: *KeepAlive, vm: *JSC.VirtualMachine) void {
if (this.status != .active)
return;
this.status = .inactive;
vm.event_loop_handle.?.unref();
}
/// From another thread, Prevent a poll from keeping the process alive.
pub fn unrefConcurrently(this: *KeepAlive, vm: *JSC.VirtualMachine) void {
if (this.status != .active)
return;
this.status = .inactive;
vm.event_loop_handle.?.unrefConcurrently();
}
/// Prevent a poll from keeping the process alive on the next tick.
pub fn unrefOnNextTick(this: *KeepAlive, vm: *JSC.VirtualMachine) void {
if (this.status != .active)
return;
this.status = .inactive;
vm.pending_unref_counter +|= 1;
}
/// From another thread, prevent a poll from keeping the process alive on the next tick.
pub fn unrefOnNextTickConcurrently(this: *KeepAlive, vm: *JSC.VirtualMachine) void {
if (this.status != .active)
return;
this.status = .inactive;
_ = @atomicRmw(@TypeOf(vm.pending_unref_counter), &vm.pending_unref_counter, .Add, 1, .Monotonic);
}
/// Allow a poll to keep the process alive.
pub fn ref(this: *KeepAlive, vm: *JSC.VirtualMachine) void {
if (this.status != .inactive)
return;
this.status = .active;
vm.event_loop_handle.?.ref();
}
/// Allow a poll to keep the process alive.
pub fn refConcurrently(this: *KeepAlive, vm: *JSC.VirtualMachine) void {
if (this.status != .inactive)
return;
this.status = .active;
vm.event_loop_handle.?.refConcurrently();
}
pub fn refConcurrentlyFromEventLoop(this: *KeepAlive, loop: *JSC.EventLoop) void {
this.refConcurrently(loop.virtual_machine);
}
pub fn unrefConcurrentlyFromEventLoop(this: *KeepAlive, loop: *JSC.EventLoop) void {
this.unrefConcurrently(loop.virtual_machine);
}
};
const KQueueGenerationNumber = if (Environment.isMac and Environment.allow_assert) usize else u0;
pub const FilePoll = struct {
var max_generation_number: KQueueGenerationNumber = 0;
fd: bun.UFileDescriptor = invalid_fd,
flags: Flags.Set = Flags.Set{},
owner: Owner = undefined,
/// We re-use FilePoll objects to avoid allocating new ones.
///
/// That means we might run into situations where the event is stale.
/// on macOS kevent64 has an extra pointer field so we use it for that
/// linux doesn't have a field like that
generation_number: KQueueGenerationNumber = 0,
next_to_free: ?*FilePoll = null,
const FileReader = JSC.WebCore.FileReader;
const FileSink = JSC.WebCore.FileSink;
const FIFO = JSC.WebCore.FIFO;
const Subprocess = JSC.Subprocess;
const BufferedInput = Subprocess.BufferedInput;
const BufferedOutput = Subprocess.BufferedOutput;
const DNSResolver = JSC.DNS.DNSResolver;
const GetAddrInfoRequest = JSC.DNS.GetAddrInfoRequest;
const Deactivated = opaque {
pub var owner: Owner = Owner.init(@as(*Deactivated, @ptrFromInt(@as(usize, 0xDEADBEEF))));
};
pub const Owner = bun.TaggedPointerUnion(.{
FileReader,
FileSink,
Subprocess,
BufferedInput,
FIFO,
Deactivated,
DNSResolver,
GetAddrInfoRequest,
});
fn updateFlags(poll: *FilePoll, updated: Flags.Set) void {
var flags = poll.flags;
flags.remove(.readable);
flags.remove(.writable);
flags.remove(.process);
flags.remove(.machport);
flags.remove(.eof);
flags.remove(.hup);
flags.setUnion(updated);
poll.flags = flags;
}
pub fn onKQueueEvent(poll: *FilePoll, loop: *Loop, kqueue_event: *const std.os.system.kevent64_s) void {
if (KQueueGenerationNumber != u0)
std.debug.assert(poll.generation_number == kqueue_event.ext[0]);
poll.updateFlags(Flags.fromKQueueEvent(kqueue_event.*));
poll.onUpdate(loop, kqueue_event.data);
}
pub fn onEpollEvent(poll: *FilePoll, loop: *Loop, epoll_event: *std.os.linux.epoll_event) void {
poll.updateFlags(Flags.fromEpollEvent(epoll_event.*));
poll.onUpdate(loop, 0);
}
pub fn clearEvent(poll: *FilePoll, flag: Flags) void {
poll.flags.remove(flag);
}
pub fn isReadable(this: *FilePoll) bool {
const readable = this.flags.contains(.readable);
this.flags.remove(.readable);
return readable;
}
pub fn isHUP(this: *FilePoll) bool {
const readable = this.flags.contains(.hup);
this.flags.remove(.hup);
return readable;
}
pub fn isEOF(this: *FilePoll) bool {
const readable = this.flags.contains(.eof);
this.flags.remove(.eof);
return readable;
}
pub fn isWritable(this: *FilePoll) bool {
const readable = this.flags.contains(.writable);
this.flags.remove(.writable);
return readable;
}
pub fn deinit(this: *FilePoll) void {
var vm = JSC.VirtualMachine.get();
this.deinitWithVM(vm);
}
fn deinitPossiblyDefer(this: *FilePoll, vm: *JSC.VirtualMachine, loop: *Loop, polls: *FilePoll.Store) void {
if (this.isRegistered()) {
_ = this.unregister(loop);
}
this.owner = Deactivated.owner;
const was_ever_registered = this.flags.contains(.was_ever_registered);
this.flags = Flags.Set{};
this.fd = invalid_fd;
polls.put(this, vm, was_ever_registered);
}
pub fn deinitWithVM(this: *FilePoll, vm: *JSC.VirtualMachine) void {
var loop = vm.event_loop_handle.?;
this.deinitPossiblyDefer(vm, loop, vm.rareData().filePolls(vm));
}
pub fn isRegistered(this: *const FilePoll) bool {
return this.flags.contains(.poll_writable) or this.flags.contains(.poll_readable) or this.flags.contains(.poll_process) or this.flags.contains(.poll_machport);
}
const kqueue_or_epoll = if (Environment.isMac) "kevent" else "epoll";
pub fn onUpdate(poll: *FilePoll, loop: *Loop, size_or_offset: i64) void {
if (poll.flags.contains(.one_shot) and !poll.flags.contains(.needs_rearm)) {
if (poll.flags.contains(.has_incremented_poll_count)) poll.deactivate(loop);
poll.flags.insert(.needs_rearm);
}
var ptr = poll.owner;
switch (ptr.tag()) {
@field(Owner.Tag, "FIFO") => {
log("onUpdate " ++ kqueue_or_epoll ++ " (fd: {d}) FIFO", .{poll.fd});
ptr.as(FIFO).ready(size_or_offset, poll.flags.contains(.hup));
},
@field(Owner.Tag, "Subprocess") => {
log("onUpdate " ++ kqueue_or_epoll ++ " (fd: {d}) Subprocess", .{poll.fd});
var loader = ptr.as(JSC.Subprocess);
loader.onExitNotification();
},
@field(Owner.Tag, "FileSink") => {
log("onUpdate " ++ kqueue_or_epoll ++ " (fd: {d}) FileSink", .{poll.fd});
var loader = ptr.as(JSC.WebCore.FileSink);
loader.onPoll(size_or_offset, 0);
},
@field(Owner.Tag, "DNSResolver") => {
log("onUpdate " ++ kqueue_or_epoll ++ " (fd: {d}) DNSResolver", .{poll.fd});
var loader: *DNSResolver = ptr.as(DNSResolver);
loader.onDNSPoll(poll);
},
@field(Owner.Tag, "GetAddrInfoRequest") => {
log("onUpdate " ++ kqueue_or_epoll ++ " (fd: {d}) GetAddrInfoRequest", .{poll.fd});
var loader: *GetAddrInfoRequest = ptr.as(GetAddrInfoRequest);
loader.onMachportChange();
},
else => {
log("onUpdate " ++ kqueue_or_epoll ++ " (fd: {d}) disconnected?", .{poll.fd});
},
}
}
pub const Flags = enum {
// What are we asking the event loop about?
/// Poll for readable events
poll_readable,
/// Poll for writable events
poll_writable,
/// Poll for process-related events
poll_process,
/// Poll for machport events
poll_machport,
// What did the event loop tell us?
readable,
writable,
process,
eof,
hup,
machport,
// What is the type of file descriptor?
fifo,
tty,
one_shot,
needs_rearm,
has_incremented_poll_count,
disable,
nonblocking,
was_ever_registered,
ignore_updates,
pub fn poll(this: Flags) Flags {
return switch (this) {
.readable => .poll_readable,
.writable => .poll_writable,
.process => .poll_process,
.machport => .poll_machport,
else => this,
};
}
pub const Set = std.EnumSet(Flags);
pub const Struct = std.enums.EnumFieldStruct(Flags, bool, false);
pub fn fromKQueueEvent(kqueue_event: std.os.system.kevent64_s) Flags.Set {
var flags = Flags.Set{};
if (kqueue_event.filter == std.os.system.EVFILT_READ) {
flags.insert(Flags.readable);
log("readable", .{});
if (kqueue_event.flags & std.os.system.EV_EOF != 0) {
flags.insert(Flags.hup);
log("hup", .{});
}
} else if (kqueue_event.filter == std.os.system.EVFILT_WRITE) {
flags.insert(Flags.writable);
log("writable", .{});
if (kqueue_event.flags & std.os.system.EV_EOF != 0) {
flags.insert(Flags.hup);
log("hup", .{});
}
} else if (kqueue_event.filter == std.os.system.EVFILT_PROC) {
log("proc", .{});
flags.insert(Flags.process);
} else if (kqueue_event.filter == std.os.system.EVFILT_MACHPORT) {
log("machport", .{});
flags.insert(Flags.machport);
}
return flags;
}
pub fn fromEpollEvent(epoll: std.os.linux.epoll_event) Flags.Set {
var flags = Flags.Set{};
if (epoll.events & std.os.linux.EPOLL.IN != 0) {
flags.insert(Flags.readable);
log("readable", .{});
}
if (epoll.events & std.os.linux.EPOLL.OUT != 0) {
flags.insert(Flags.writable);
log("writable", .{});
}
if (epoll.events & std.os.linux.EPOLL.ERR != 0) {
flags.insert(Flags.eof);
log("eof", .{});
}
if (epoll.events & std.os.linux.EPOLL.HUP != 0) {
flags.insert(Flags.hup);
log("hup", .{});
}
return flags;
}
};
const HiveArray = bun.HiveArray(FilePoll, 128).Fallback;
// We defer freeing FilePoll until the end of the next event loop iteration
// This ensures that we don't free a FilePoll before the next callback is called
pub const Store = struct {
hive: HiveArray,
pending_free_head: ?*FilePoll = null,
pending_free_tail: ?*FilePoll = null,
const log = Output.scoped(.FilePoll, false);
pub fn init(allocator: std.mem.Allocator) Store {
return .{
.hive = HiveArray.init(allocator),
};
}
pub fn get(this: *Store) *FilePoll {
return this.hive.get();
}
pub fn processDeferredFrees(this: *Store) void {
var next = this.pending_free_head;
while (next) |current| {
next = current.next_to_free;
current.next_to_free = null;
this.hive.put(current);
}
this.pending_free_head = null;
this.pending_free_tail = null;
}
pub fn put(this: *Store, poll: *FilePoll, vm: *JSC.VirtualMachine, ever_registered: bool) void {
if (!ever_registered) {
this.hive.put(poll);
return;
}
std.debug.assert(poll.next_to_free == null);
if (this.pending_free_tail) |tail| {
std.debug.assert(this.pending_free_head != null);
std.debug.assert(tail.next_to_free == null);
tail.next_to_free = poll;
}
if (this.pending_free_head == null) {
this.pending_free_head = poll;
std.debug.assert(this.pending_free_tail == null);
}
poll.flags.insert(.ignore_updates);
this.pending_free_tail = poll;
std.debug.assert(vm.after_event_loop_callback == null or vm.after_event_loop_callback == @as(?JSC.OpaqueCallback, @ptrCast(&processDeferredFrees)));
vm.after_event_loop_callback = @ptrCast(&processDeferredFrees);
vm.after_event_loop_callback_ctx = this;
}
};
const log = Output.scoped(.FilePoll, false);
pub inline fn isActive(this: *const FilePoll) bool {
return this.flags.contains(.has_incremented_poll_count);
}
pub inline fn isWatching(this: *const FilePoll) bool {
return !this.flags.contains(.needs_rearm) and (this.flags.contains(.poll_readable) or this.flags.contains(.poll_writable) or this.flags.contains(.poll_process));
}
pub inline fn isKeepingProcessAlive(this: *const FilePoll) bool {
return !this.flags.contains(.disable) and this.isActive();
}
/// Make calling ref() on this poll into a no-op.
pub fn disableKeepingProcessAlive(this: *FilePoll, vm: *JSC.VirtualMachine) void {
if (this.flags.contains(.disable))
return;
this.flags.insert(.disable);
vm.event_loop_handle.?.active -= @as(u32, @intFromBool(this.flags.contains(.has_incremented_poll_count)));
}
pub fn enableKeepingProcessAlive(this: *FilePoll, vm: *JSC.VirtualMachine) void {
if (!this.flags.contains(.disable))
return;
this.flags.remove(.disable);
vm.event_loop_handle.?.active += @as(u32, @intFromBool(this.flags.contains(.has_incremented_poll_count)));
}
pub fn canActivate(this: *const FilePoll) bool {
return !this.flags.contains(.has_incremented_poll_count);
}
/// Only intended to be used from EventLoop.Pollable
pub fn deactivate(this: *FilePoll, loop: *Loop) void {
std.debug.assert(this.flags.contains(.has_incremented_poll_count));
loop.num_polls -= @as(i32, @intFromBool(this.flags.contains(.has_incremented_poll_count)));
loop.active -|= @as(u32, @intFromBool(!this.flags.contains(.disable) and this.flags.contains(.has_incremented_poll_count)));
this.flags.remove(.has_incremented_poll_count);
}
/// Only intended to be used from EventLoop.Pollable
pub fn activate(this: *FilePoll, loop: *Loop) void {
loop.num_polls += @as(i32, @intFromBool(!this.flags.contains(.has_incremented_poll_count)));
loop.active += @as(u32, @intFromBool(!this.flags.contains(.disable) and !this.flags.contains(.has_incremented_poll_count)));
this.flags.insert(.has_incremented_poll_count);
}
pub fn init(vm: *JSC.VirtualMachine, fd: bun.FileDescriptor, flags: Flags.Struct, comptime Type: type, owner: *Type) *FilePoll {
return initWithOwner(vm, fd, flags, Owner.init(owner));
}
pub fn initWithOwner(vm: *JSC.VirtualMachine, fd: bun.FileDescriptor, flags: Flags.Struct, owner: Owner) *FilePoll {
var poll = vm.rareData().filePolls(vm).get();
poll.fd = @intCast(fd);
poll.flags = Flags.Set.init(flags);
poll.owner = owner;
poll.next_to_free = null;
if (KQueueGenerationNumber != u0) {
max_generation_number +%= 1;
poll.generation_number = max_generation_number;
}
return poll;
}
pub inline fn canRef(this: *const FilePoll) bool {
if (this.flags.contains(.disable))
return false;
return !this.flags.contains(.has_incremented_poll_count);
}
pub inline fn canUnref(this: *const FilePoll) bool {
return this.flags.contains(.has_incremented_poll_count);
}
/// Prevent a poll from keeping the process alive.
pub fn unref(this: *FilePoll, vm: *JSC.VirtualMachine) void {
if (!this.canUnref())
return;
log("unref", .{});
this.deactivate(vm.event_loop_handle.?);
}
/// Allow a poll to keep the process alive.
pub fn ref(this: *FilePoll, vm: *JSC.VirtualMachine) void {
if (this.canRef())
return;
log("ref", .{});
this.activate(vm.event_loop_handle.?);
}
pub fn onTick(loop: *Loop, tagged_pointer: ?*anyopaque) callconv(.C) void {
var tag = Pollable.from(tagged_pointer);
if (tag.tag() != @field(Pollable.Tag, "FilePoll"))
return;
var file_poll: *FilePoll = tag.as(FilePoll);
if (file_poll.flags.contains(.ignore_updates)) {
return;
}
if (comptime Environment.isMac)
onKQueueEvent(file_poll, loop, &loop.ready_polls[@as(usize, @intCast(loop.current_ready_poll))])
else if (comptime Environment.isLinux)
onEpollEvent(file_poll, loop, &loop.ready_polls[@as(usize, @intCast(loop.current_ready_poll))]);
}
const Pollable = bun.TaggedPointerUnion(
.{
FilePoll,
Deactivated,
},
);
comptime {
@export(onTick, .{ .name = "Bun__internal_dispatch_ready_poll" });
}
const timeout = std.mem.zeroes(std.os.timespec);
const kevent = std.c.kevent;
const linux = std.os.linux;
pub fn register(this: *FilePoll, loop: *Loop, flag: Flags, one_shot: bool) JSC.Maybe(void) {
return registerWithFd(this, loop, flag, one_shot, this.fd);
}
pub fn registerWithFd(this: *FilePoll, loop: *Loop, flag: Flags, one_shot: bool, fd: u64) JSC.Maybe(void) {
const watcher_fd = loop.fd;
log("register: {s} ({d})", .{ @tagName(flag), fd });
std.debug.assert(fd != invalid_fd);
if (one_shot) {
this.flags.insert(.one_shot);
}
if (comptime Environment.isLinux) {
const one_shot_flag: u32 = if (!this.flags.contains(.one_shot)) 0 else linux.EPOLL.ONESHOT;
const flags: u32 = switch (flag) {
.process,
.readable,
=> linux.EPOLL.IN | linux.EPOLL.HUP | one_shot_flag,
.writable => linux.EPOLL.OUT | linux.EPOLL.HUP | linux.EPOLL.ERR | one_shot_flag,
else => unreachable,
};
var event = linux.epoll_event{ .events = flags, .data = .{ .u64 = @intFromPtr(Pollable.init(this).ptr()) } };
const ctl = linux.epoll_ctl(
watcher_fd,
if (this.isRegistered() or this.flags.contains(.needs_rearm)) linux.EPOLL.CTL_MOD else linux.EPOLL.CTL_ADD,
@as(std.os.fd_t, @intCast(fd)),
&event,
);
this.flags.insert(.was_ever_registered);
if (JSC.Maybe(void).errnoSys(ctl, .epoll_ctl)) |errno| {
return errno;
}
} else if (comptime Environment.isMac) {
var changelist = std.mem.zeroes([2]std.os.system.kevent64_s);
const one_shot_flag: u16 = if (!this.flags.contains(.one_shot)) 0 else std.c.EV_ONESHOT;
changelist[0] = switch (flag) {
.readable => .{
.ident = @as(u64, @intCast(fd)),
.filter = std.os.system.EVFILT_READ,
.data = 0,
.fflags = 0,
.udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_ADD | one_shot_flag,
.ext = .{ this.generation_number, 0 },
},
.writable => .{
.ident = @as(u64, @intCast(fd)),
.filter = std.os.system.EVFILT_WRITE,
.data = 0,
.fflags = 0,
.udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_ADD | one_shot_flag,
.ext = .{ this.generation_number, 0 },
},
.process => .{
.ident = @as(u64, @intCast(fd)),
.filter = std.os.system.EVFILT_PROC,
.data = 0,
.fflags = std.c.NOTE_EXIT,
.udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_ADD | one_shot_flag,
.ext = .{ this.generation_number, 0 },
},
.machport => .{
.ident = @as(u64, @intCast(fd)),
.filter = std.os.system.EVFILT_MACHPORT,
.data = 0,
.fflags = 0,
.udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_ADD | one_shot_flag,
.ext = .{ this.generation_number, 0 },
},
else => unreachable,
};
// output events only include change errors
const KEVENT_FLAG_ERROR_EVENTS = 0x000002;
// The kevent() system call returns the number of events placed in
// the eventlist, up to the value given by nevents. If the time
// limit expires, then kevent() returns 0.
const rc = rc: {
while (true) {
const rc = std.os.system.kevent64(
watcher_fd,
&changelist,
1,
// The same array may be used for the changelist and eventlist.
&changelist,
// we set 0 here so that if we get an error on
// registration, it becomes errno
0,
KEVENT_FLAG_ERROR_EVENTS,
&timeout,
);
if (std.c.getErrno(rc) == .INTR) continue;
break :rc rc;
}
};
this.flags.insert(.was_ever_registered);
// If an error occurs while
// processing an element of the changelist and there is enough room
// in the eventlist, then the event will be placed in the eventlist
// with EV_ERROR set in flags and the system error in data.
if (changelist[0].flags == std.c.EV_ERROR and changelist[0].data != 0) {
return JSC.Maybe(void).errnoSys(changelist[0].data, .kevent).?;
// Otherwise, -1 will be returned, and errno will be set to
// indicate the error condition.
}
const errno = std.c.getErrno(rc);
if (errno != .SUCCESS) {
return JSC.Maybe(void){
.err = bun.sys.Error.fromCode(errno, .kqueue),
};
}
} else {
bun.todo(@src(), {});
}
if (this.canActivate())
this.activate(loop);
this.flags.insert(switch (flag) {
.readable => .poll_readable,
.process => if (comptime Environment.isLinux) .poll_readable else .poll_process,
.writable => .poll_writable,
.machport => .poll_machport,
else => unreachable,
});
this.flags.remove(.needs_rearm);
return JSC.Maybe(void).success;
}
const invalid_fd = bun.invalid_fd;
pub fn unregister(this: *FilePoll, loop: *Loop) JSC.Maybe(void) {
return this.unregisterWithFd(loop, this.fd);
}
pub fn unregisterWithFd(this: *FilePoll, loop: *Loop, fd: bun.UFileDescriptor) JSC.Maybe(void) {
if (!(this.flags.contains(.poll_readable) or this.flags.contains(.poll_writable) or this.flags.contains(.poll_process) or this.flags.contains(.poll_machport))) {
// no-op
return JSC.Maybe(void).success;
}
std.debug.assert(fd != invalid_fd);
const watcher_fd = loop.fd;
const flag: Flags = brk: {
if (this.flags.contains(.poll_readable))
break :brk .readable;
if (this.flags.contains(.poll_writable))
break :brk .writable;
if (this.flags.contains(.poll_process))
break :brk .process;
if (this.flags.contains(.poll_machport))
break :brk .machport;
return JSC.Maybe(void).success;
};
if (this.flags.contains(.needs_rearm)) {
log("unregister: {s} ({d}) skipped due to needs_rearm", .{ @tagName(flag), fd });
this.flags.remove(.poll_process);
this.flags.remove(.poll_readable);
this.flags.remove(.poll_process);
this.flags.remove(.poll_machport);
return JSC.Maybe(void).success;
}
log("unregister: {s} ({d})", .{ @tagName(flag), fd });
if (comptime Environment.isLinux) {
const ctl = linux.epoll_ctl(
watcher_fd,
linux.EPOLL.CTL_DEL,
@as(std.os.fd_t, @intCast(fd)),
null,
);
if (JSC.Maybe(void).errnoSys(ctl, .epoll_ctl)) |errno| {
return errno;
}
} else if (comptime Environment.isMac) {
var changelist = std.mem.zeroes([2]std.os.system.kevent64_s);
changelist[0] = switch (flag) {
.readable => .{
.ident = @as(u64, @intCast(fd)),
.filter = std.os.system.EVFILT_READ,
.data = 0,
.fflags = 0,
.udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_DELETE,
.ext = .{ 0, 0 },
},
.machport => .{
.ident = @as(u64, @intCast(fd)),
.filter = std.os.system.EVFILT_MACHPORT,
.data = 0,
.fflags = 0,
.udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_DELETE,
.ext = .{ 0, 0 },
},
.writable => .{
.ident = @as(u64, @intCast(fd)),
.filter = std.os.system.EVFILT_WRITE,
.data = 0,
.fflags = 0,
.udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_DELETE,
.ext = .{ 0, 0 },
},
.process => .{
.ident = @as(u64, @intCast(fd)),
.filter = std.os.system.EVFILT_PROC,
.data = 0,
.fflags = std.c.NOTE_EXIT,
.udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_DELETE,
.ext = .{ 0, 0 },
},
else => unreachable,
};
// output events only include change errors
const KEVENT_FLAG_ERROR_EVENTS = 0x000002;
// The kevent() system call returns the number of events placed in
// the eventlist, up to the value given by nevents. If the time
// limit expires, then kevent() returns 0.
const rc = std.os.system.kevent64(
watcher_fd,
&changelist,
1,
// The same array may be used for the changelist and eventlist.
&changelist,
1,
KEVENT_FLAG_ERROR_EVENTS,
&timeout,
);
// If an error occurs while
// processing an element of the changelist and there is enough room
// in the eventlist, then the event will be placed in the eventlist
// with EV_ERROR set in flags and the system error in data.
if (changelist[0].flags == std.c.EV_ERROR) {
return JSC.Maybe(void).errnoSys(changelist[0].data, .kevent).?;
// Otherwise, -1 will be returned, and errno will be set to
// indicate the error condition.
}
const errno = std.c.getErrno(rc);
switch (rc) {
std.math.minInt(@TypeOf(rc))...-1 => return JSC.Maybe(void).errnoSys(@intFromEnum(errno), .kevent).?,
else => {},
}
} else {
bun.todo(@src(), {});
}
this.flags.remove(.needs_rearm);
this.flags.remove(.one_shot);
// we don't support both right now
std.debug.assert(!(this.flags.contains(.poll_readable) and this.flags.contains(.poll_writable)));
this.flags.remove(.poll_readable);
this.flags.remove(.poll_writable);
this.flags.remove(.poll_process);
this.flags.remove(.poll_machport);
if (this.isActive())
this.deactivate(loop);
return JSC.Maybe(void).success;
}
};
pub const Waker = @import("io").Waker;

View File

@@ -0,0 +1,3 @@
pub const Loop = opaque {};
pub const KeepAlive = opaque {};
pub const FilePoll = opaque {};

View File

@@ -0,0 +1,340 @@
const bun = @import("root").bun;
const Output = bun.Output;
const JSC = bun.JSC;
const uws = bun.uws;
const Environment = bun.Environment;
const std = @import("std");
const uv = bun.windows.libuv;
pub const Loop = uv.Loop;
pub const KeepAlive = struct {
// handle.init zeroes the memory
handle: uv.uv_async_t = undefined,
status: Status = .inactive,
const log = Output.scoped(.KeepAlive, false);
const Status = enum { active, inactive, done };
pub inline fn isActive(this: KeepAlive) bool {
if (comptime Environment.allow_assert) {
if (this.status == .active) {
std.debug.assert(this.handle.isActive());
}
}
return this.status == .active;
}
/// Make calling ref() on this poll into a no-op.
pub fn disable(this: *KeepAlive) void {
if (this.status == .active) {
this.unref(JSC.VirtualMachine.get());
this.handle.close(null);
}
this.status = .done;
}
/// Only intended to be used from EventLoop.Pollable
pub fn deactivate(this: *KeepAlive, loop: *Loop) void {
_ = loop;
if (this.status != .active)
return;
this.status = .inactive;
this.handle.close(null);
}
/// Only intended to be used from EventLoop.Pollable
pub fn activate(this: *KeepAlive, loop: *Loop) void {
if (this.status != .active)
return;
this.status = .active;
this.handle.init(loop, null);
}
pub fn init() KeepAlive {
return .{};
}
/// Prevent a poll from keeping the process alive.
pub fn unref(this: *KeepAlive, vm: *JSC.VirtualMachine) void {
_ = vm;
if (this.status != .active)
return;
this.status = .inactive;
this.handle.unref();
}
/// From another thread, Prevent a poll from keeping the process alive.
pub fn unrefConcurrently(this: *KeepAlive, vm: *JSC.VirtualMachine) void {
_ = vm;
if (this.status != .active)
return;
this.status = .inactive;
this.handle.unref();
}
/// Prevent a poll from keeping the process alive on the next tick.
pub fn unrefOnNextTick(this: *KeepAlive, vm: *JSC.VirtualMachine) void {
_ = vm;
if (this.status != .active)
return;
this.status = .inactive;
this.handle.unref();
}
/// From another thread, prevent a poll from keeping the process alive on the next tick.
pub fn unrefOnNextTickConcurrently(this: *KeepAlive, vm: *JSC.VirtualMachine) void {
_ = vm;
if (this.status != .active)
return;
this.status = .inactive;
this.handle.unref();
}
/// Allow a poll to keep the process alive.
pub fn ref(this: *KeepAlive, vm: *JSC.VirtualMachine) void {
if (this.status != .inactive)
return;
this.status = .active;
this.handle.init(vm.event_loop_handle.?, null);
this.handle.ref();
}
/// Allow a poll to keep the process alive.
pub fn refConcurrently(this: *KeepAlive, vm: *JSC.VirtualMachine) void {
if (this.status != .inactive)
return;
this.status = .active;
this.handle.init(vm.event_loop_handle.?, null);
this.handle.ref();
}
pub fn refConcurrentlyFromEventLoop(this: *KeepAlive, loop: *JSC.EventLoop) void {
this.refConcurrently(loop.virtual_machine);
}
pub fn unrefConcurrentlyFromEventLoop(this: *KeepAlive, loop: *JSC.EventLoop) void {
this.unrefConcurrently(loop.virtual_machine);
}
};
const Posix = @import("./posix_event_loop.zig");
pub const FilePoll = struct {
fd: bun.FileDescriptor,
owner: Owner = undefined,
flags: Flags.Set = Flags.Set{},
next_to_free: ?*FilePoll = null,
pub const Flags = Posix.FilePoll.Flags;
pub const Owner = Posix.FilePoll.Owner;
const log = Output.scoped(.FilePoll, false);
pub inline fn isActive(this: *const FilePoll) bool {
return this.flags.contains(.has_incremented_poll_count);
}
pub inline fn isWatching(this: *const FilePoll) bool {
return !this.flags.contains(.needs_rearm) and (this.flags.contains(.poll_readable) or this.flags.contains(.poll_writable) or this.flags.contains(.poll_process));
}
pub inline fn isKeepingProcessAlive(this: *const FilePoll) bool {
return !this.flags.contains(.disable) and this.isActive();
}
pub fn isRegistered(this: *const FilePoll) bool {
return this.flags.contains(.poll_writable) or this.flags.contains(.poll_readable) or this.flags.contains(.poll_process) or this.flags.contains(.poll_machport);
}
/// Make calling ref() on this poll into a no-op.
pub fn disableKeepingProcessAlive(this: *FilePoll, vm: *JSC.VirtualMachine) void {
if (this.flags.contains(.disable))
return;
this.flags.insert(.disable);
vm.event_loop_handle.?.active_handles -= @as(u32, @intFromBool(this.flags.contains(.has_incremented_poll_count)));
}
pub fn init(vm: *JSC.VirtualMachine, fd: bun.FileDescriptor, flags: Flags.Struct, comptime Type: type, owner: *Type) *FilePoll {
return initWithOwner(vm, fd, flags, Owner.init(owner));
}
pub fn initWithOwner(vm: *JSC.VirtualMachine, fd: bun.FileDescriptor, flags: Flags.Struct, owner: Owner) *FilePoll {
var poll = vm.rareData().filePolls(vm).get();
poll.fd = fd;
poll.flags = Flags.Set.init(flags);
poll.owner = owner;
poll.next_to_free = null;
return poll;
}
pub fn deinit(this: *FilePoll) void {
var vm = JSC.VirtualMachine.get();
this.deinitWithVM(vm);
}
pub fn unregister(this: *FilePoll, loop: *Loop) bool {
_ = loop;
uv.uv_unref(@ptrFromInt(this.fd));
return true;
}
fn deinitPossiblyDefer(this: *FilePoll, vm: *JSC.VirtualMachine, loop: *Loop, polls: *FilePoll.Store) void {
if (this.isRegistered()) {
_ = this.unregister(loop);
}
const was_ever_registered = this.flags.contains(.was_ever_registered);
this.flags = Flags.Set{};
this.fd = bun.invalid_fd;
polls.put(this, vm, was_ever_registered);
}
pub fn isReadable(this: *FilePoll) bool {
const readable = this.flags.contains(.readable);
this.flags.remove(.readable);
return readable;
}
pub fn isHUP(this: *FilePoll) bool {
const readable = this.flags.contains(.hup);
this.flags.remove(.hup);
return readable;
}
pub fn isEOF(this: *FilePoll) bool {
const readable = this.flags.contains(.eof);
this.flags.remove(.eof);
return readable;
}
pub fn clearEvent(poll: *FilePoll, flag: Flags) void {
poll.flags.remove(flag);
}
pub fn isWritable(this: *FilePoll) bool {
const readable = this.flags.contains(.writable);
this.flags.remove(.writable);
return readable;
}
pub fn deinitWithVM(this: *FilePoll, vm: *JSC.VirtualMachine) void {
var loop = vm.event_loop_handle.?;
this.deinitPossiblyDefer(vm, loop, vm.rareData().filePolls(vm));
}
pub fn enableKeepingProcessAlive(this: *FilePoll, vm: *JSC.VirtualMachine) void {
if (!this.flags.contains(.disable))
return;
this.flags.remove(.disable);
vm.event_loop_handle.?.active_handles += @as(u32, @intFromBool(this.flags.contains(.has_incremented_poll_count)));
}
pub fn canActivate(this: *const FilePoll) bool {
return !this.flags.contains(.has_incremented_poll_count);
}
/// Only intended to be used from EventLoop.Pollable
pub fn deactivate(this: *FilePoll, loop: *Loop) void {
std.debug.assert(this.flags.contains(.has_incremented_poll_count));
loop.active_handles -= @as(u32, @intFromBool(!this.flags.contains(.disable) and this.flags.contains(.has_incremented_poll_count)));
this.flags.remove(.has_incremented_poll_count);
}
/// Only intended to be used from EventLoop.Pollable
pub fn activate(this: *FilePoll, loop: *Loop) void {
loop.active_handles += @as(u32, @intFromBool(!this.flags.contains(.disable) and !this.flags.contains(.has_incremented_poll_count)));
this.flags.insert(.has_incremented_poll_count);
}
pub inline fn canRef(this: *const FilePoll) bool {
if (this.flags.contains(.disable))
return false;
return !this.flags.contains(.has_incremented_poll_count);
}
pub inline fn canUnref(this: *const FilePoll) bool {
return this.flags.contains(.has_incremented_poll_count);
}
/// Prevent a poll from keeping the process alive.
pub fn unref(this: *FilePoll, vm: *JSC.VirtualMachine) void {
if (!this.canUnref())
return;
log("unref", .{});
this.deactivate(vm.event_loop_handle.?);
}
/// Allow a poll to keep the process alive.
pub fn ref(this: *FilePoll, vm: *JSC.VirtualMachine) void {
if (this.canRef())
return;
log("ref", .{});
this.activate(vm.event_loop_handle.?);
}
const HiveArray = bun.HiveArray(FilePoll, 128).Fallback;
pub const Store = struct {
hive: HiveArray,
pending_free_head: ?*FilePoll = null,
pending_free_tail: ?*FilePoll = null,
const log = Output.scoped(.FilePoll, false);
pub fn init(allocator: std.mem.Allocator) Store {
return .{
.hive = HiveArray.init(allocator),
};
}
pub fn get(this: *Store) *FilePoll {
return this.hive.get();
}
pub fn processDeferredFrees(this: *Store) void {
var next = this.pending_free_head;
while (next) |current| {
next = current.next_to_free;
current.next_to_free = null;
this.hive.put(current);
}
this.pending_free_head = null;
this.pending_free_tail = null;
}
pub fn put(this: *Store, poll: *FilePoll, vm: *JSC.VirtualMachine, ever_registered: bool) void {
if (!ever_registered) {
this.hive.put(poll);
return;
}
std.debug.assert(poll.next_to_free == null);
if (this.pending_free_tail) |tail| {
std.debug.assert(this.pending_free_head != null);
std.debug.assert(tail.next_to_free == null);
tail.next_to_free = poll;
}
if (this.pending_free_head == null) {
this.pending_free_head = poll;
std.debug.assert(this.pending_free_tail == null);
}
poll.flags.insert(.ignore_updates);
this.pending_free_tail = poll;
std.debug.assert(vm.after_event_loop_callback == null or vm.after_event_loop_callback == @as(?JSC.OpaqueCallback, @ptrCast(&processDeferredFrees)));
vm.after_event_loop_callback = @ptrCast(&processDeferredFrees);
vm.after_event_loop_callback_ctx = this;
}
};
};

View File

@@ -1 +1 @@
0
0

View File

@@ -204,7 +204,6 @@ const MarkedArrayBuffer = @import("../base.zig").MarkedArrayBuffer;
const getAllocator = @import("../base.zig").getAllocator;
const JSValue = @import("root").bun.JSC.JSValue;
const Microtask = @import("root").bun.JSC.Microtask;
const JSGlobalObject = @import("root").bun.JSC.JSGlobalObject;
const ExceptionValueRef = @import("root").bun.JSC.ExceptionValueRef;
const JSPrivateDataPtr = @import("root").bun.JSC.JSPrivateDataPtr;
@@ -234,6 +233,7 @@ const Which = @import("../../which.zig");
const ErrorableString = JSC.ErrorableString;
const is_bindgen = JSC.is_bindgen;
const max_addressible_memory = std.math.maxInt(u56);
const Async = bun.Async;
threadlocal var css_imports_list_strings: [512]ZigString = undefined;
threadlocal var css_imports_list: [512]Api.StringPointer = undefined;
@@ -1543,12 +1543,12 @@ pub const Crypto = struct {
promise: JSC.JSPromise.Strong,
event_loop: *JSC.EventLoop,
global: *JSC.JSGlobalObject,
ref: JSC.PollRef = .{},
ref: Async.KeepAlive = .{},
task: JSC.WorkPoolTask = .{ .callback = &run },
pub const Result = struct {
value: Value,
ref: JSC.PollRef = .{},
ref: Async.KeepAlive = .{},
task: JSC.AnyTask = undefined,
promise: JSC.JSPromise.Strong,
@@ -1793,12 +1793,12 @@ pub const Crypto = struct {
promise: JSC.JSPromise.Strong,
event_loop: *JSC.EventLoop,
global: *JSC.JSGlobalObject,
ref: JSC.PollRef = .{},
ref: Async.KeepAlive = .{},
task: JSC.WorkPoolTask = .{ .callback = &run },
pub const Result = struct {
value: Value,
ref: JSC.PollRef = .{},
ref: Async.KeepAlive = .{},
task: JSC.AnyTask = undefined,
promise: JSC.JSPromise.Strong,
@@ -3325,7 +3325,8 @@ pub const Timer = struct {
if (val.did_unref_timer) {
val.did_unref_timer = false;
vm.event_loop_handle.?.num_polls += 1;
if (comptime Environment.isPosix)
vm.event_loop_handle.?.num_polls += 1;
}
}
}
@@ -3398,7 +3399,7 @@ pub const Timer = struct {
.callback = JSC.Strong.create(callback, globalThis),
.globalThis = globalThis,
.timer = uws.Timer.create(
vm.event_loop_handle.?,
vm.uwsLoop(),
id,
),
};
@@ -3444,7 +3445,8 @@ pub const Timer = struct {
if (!val.did_unref_timer) {
val.did_unref_timer = true;
vm.event_loop_handle.?.num_polls -= 1;
if (comptime Environment.isPosix)
vm.event_loop_handle.?.num_polls -= 1;
}
}
}
@@ -3474,7 +3476,7 @@ pub const Timer = struct {
globalThis: *JSC.JSGlobalObject,
timer: *uws.Timer,
did_unref_timer: bool = false,
poll_ref: JSC.PollRef = JSC.PollRef.init(),
poll_ref: Async.KeepAlive = Async.KeepAlive.init(),
arguments: JSC.Strong = .{},
has_scheduled_job: bool = false,
@@ -3596,8 +3598,9 @@ pub const Timer = struct {
this.timer.deinit();
// balance double unreffing in doUnref
vm.event_loop_handle.?.num_polls += @as(i32, @intFromBool(this.did_unref_timer));
if (comptime Environment.isPosix)
// balance double unreffing in doUnref
vm.event_loop_handle.?.num_polls += @as(i32, @intFromBool(this.did_unref_timer));
this.callback.deinit();
this.arguments.deinit();
@@ -3653,7 +3656,7 @@ pub const Timer = struct {
.callback = JSC.Strong.create(callback, globalThis),
.globalThis = globalThis,
.timer = uws.Timer.create(
vm.event_loop_handle.?,
vm.uwsLoop(),
Timeout.ID{
.id = id,
.kind = kind,

View File

@@ -14,7 +14,7 @@ const JSC = @import("root").bun.JSC;
const JSValue = JSC.JSValue;
const JSGlobalObject = JSC.JSGlobalObject;
const c_ares = bun.c_ares;
const Async = bun.Async;
const GetAddrInfoAsyncCallback = fn (i32, ?*std.c.addrinfo, ?*anyopaque) callconv(.C) void;
const INET6_ADDRSTRLEN = if (bun.Environment.isWindows) 65 else 46;
const IANA_DNS_PORT = 53;
@@ -42,7 +42,7 @@ const LibInfo = struct {
const RTLD_LAZY = 1;
const RTLD_LOCAL = 4;
handle = std.c.dlopen("libinfo.dylib", RTLD_LAZY | RTLD_LOCAL);
handle = bun.C.dlopen("libinfo.dylib", RTLD_LAZY | RTLD_LOCAL);
if (handle == null)
Output.debug("libinfo.dylib not found", .{});
return handle;
@@ -119,7 +119,7 @@ const LibInfo = struct {
return promise_value;
}
std.debug.assert(request.backend.libinfo.machport != null);
request.backend.libinfo.file_poll = bun.JSC.FilePoll.init(this.vm, std.math.maxInt(i32) - 1, .{}, GetAddrInfoRequest, request);
request.backend.libinfo.file_poll = bun.Async.FilePoll.init(this.vm, std.math.maxInt(i32) - 1, .{}, GetAddrInfoRequest, request);
std.debug.assert(
request.backend.libinfo.file_poll.?.registerWithFd(
this.vm.event_loop_handle.?,
@@ -644,7 +644,7 @@ pub fn ResolveInfoRequest(comptime cares_type: type, comptime type_name: []const
var hasher = std.hash.Wyhash.init(0);
hasher.update(name);
const hash = hasher.final();
var poll_ref = JSC.PollRef.init();
var poll_ref = Async.KeepAlive.init();
poll_ref.ref(globalThis.bunVM());
request.* = .{
.resolver_for_caching = resolver,
@@ -741,7 +741,7 @@ pub const GetHostByAddrInfoRequest = struct {
var hasher = std.hash.Wyhash.init(0);
hasher.update(name);
const hash = hasher.final();
var poll_ref = JSC.PollRef.init();
var poll_ref = Async.KeepAlive.init();
poll_ref.ref(globalThis.bunVM());
request.* = .{
.resolver_for_caching = resolver,
@@ -832,7 +832,7 @@ pub const GetAddrInfoRequest = struct {
comptime cache_field: []const u8,
) !*GetAddrInfoRequest {
var request = try globalThis.allocator().create(GetAddrInfoRequest);
var poll_ref = JSC.PollRef.init();
var poll_ref = Async.KeepAlive.init();
poll_ref.ref(globalThis.bunVM());
request.* = .{
.backend = backend,
@@ -964,7 +964,7 @@ pub const GetAddrInfoRequest = struct {
},
pub const LibInfo = struct {
file_poll: ?*bun.JSC.FilePoll = null,
file_poll: ?*bun.Async.FilePoll = null,
machport: ?*anyopaque = null,
extern fn getaddrinfo_send_reply(*anyopaque, *const JSC.DNS.LibInfo.GetaddrinfoAsyncHandleReply) bool;
@@ -1043,14 +1043,14 @@ pub const CAresReverse = struct {
globalThis: *JSC.JSGlobalObject = undefined,
promise: JSC.JSPromise.Strong,
poll_ref: JSC.PollRef,
poll_ref: Async.KeepAlive,
allocated: bool = false,
next: ?*@This() = null,
name: []const u8,
pub fn init(globalThis: *JSC.JSGlobalObject, allocator: std.mem.Allocator, name: []const u8) !*@This() {
var this = try allocator.create(@This());
var poll_ref = JSC.PollRef.init();
var poll_ref = Async.KeepAlive.init();
poll_ref.ref(globalThis.bunVM());
this.* = .{ .globalThis = globalThis, .promise = JSC.JSPromise.Strong.init(globalThis), .poll_ref = poll_ref, .allocated = true, .name = name };
return this;
@@ -1114,14 +1114,14 @@ pub fn CAresLookup(comptime cares_type: type, comptime type_name: []const u8) ty
globalThis: *JSC.JSGlobalObject = undefined,
promise: JSC.JSPromise.Strong,
poll_ref: JSC.PollRef,
poll_ref: Async.KeepAlive,
allocated: bool = false,
next: ?*@This() = null,
name: []const u8,
pub fn init(globalThis: *JSC.JSGlobalObject, allocator: std.mem.Allocator, name: []const u8) !*@This() {
var this = try allocator.create(@This());
var poll_ref = JSC.PollRef.init();
var poll_ref = Async.KeepAlive.init();
poll_ref.ref(globalThis.bunVM());
this.* = .{ .globalThis = globalThis, .promise = JSC.JSPromise.Strong.init(globalThis), .poll_ref = poll_ref, .allocated = true, .name = name };
return this;
@@ -1187,11 +1187,11 @@ pub const DNSLookup = struct {
promise: JSC.JSPromise.Strong,
allocated: bool = false,
next: ?*DNSLookup = null,
poll_ref: JSC.PollRef,
poll_ref: Async.KeepAlive,
pub fn init(globalThis: *JSC.JSGlobalObject, allocator: std.mem.Allocator) !*DNSLookup {
var this = try allocator.create(DNSLookup);
var poll_ref = JSC.PollRef.init();
var poll_ref = Async.KeepAlive.init();
poll_ref.ref(globalThis.bunVM());
this.* = .{
@@ -1298,7 +1298,7 @@ pub const GlobalData = struct {
global.* = .{
.resolver = .{
.vm = vm,
.polls = std.AutoArrayHashMap(i32, ?*JSC.FilePoll).init(allocator),
.polls = std.AutoArrayHashMap(i32, ?*Async.FilePoll).init(allocator),
},
};
@@ -1311,7 +1311,7 @@ pub const DNSResolver = struct {
channel: ?*c_ares.Channel = null,
vm: *JSC.VirtualMachine,
polls: std.AutoArrayHashMap(i32, ?*JSC.FilePoll) = undefined,
polls: std.AutoArrayHashMap(i32, ?*Async.FilePoll) = undefined,
pending_host_cache_cares: PendingCache = PendingCache.init(),
pending_host_cache_native: PendingCache = PendingCache.init(),
@@ -1610,7 +1610,7 @@ pub const DNSResolver = struct {
pub fn onDNSPoll(
this: *DNSResolver,
poll: *JSC.FilePoll,
poll: *Async.FilePoll,
) void {
var vm = this.vm;
defer vm.drainMicrotasks();
@@ -1634,6 +1634,11 @@ pub const DNSResolver = struct {
readable: bool,
writable: bool,
) void {
if (comptime Environment.isWindows) {
bun.todo(@src(), {});
return;
}
var vm = this.vm;
if (!readable and !writable) {
@@ -1652,7 +1657,7 @@ pub const DNSResolver = struct {
var poll_entry = this.polls.getOrPut(fd) catch unreachable;
if (!poll_entry.found_existing) {
poll_entry.value_ptr.* = JSC.FilePoll.init(vm, bun.toFD(fd), .{}, DNSResolver, this);
poll_entry.value_ptr.* = Async.FilePoll.init(vm, bun.toFD(fd), .{}, DNSResolver, this);
}
var poll = poll_entry.value_ptr.*.?;
@@ -1812,8 +1817,8 @@ pub const DNSResolver = struct {
return .zero;
}
const ip = ip_str.toSliceClone(globalThis, bun.default_allocator).slice();
const ip_slice = ip_str.toSliceClone(globalThis, bun.default_allocator);
const ip = ip_slice.slice();
var vm = globalThis.bunVM();
var resolver = vm.rareData().globalDNSResolver(vm);
var channel: *c_ares.Channel = switch (resolver.getChannel()) {
@@ -1824,7 +1829,7 @@ pub const DNSResolver = struct {
.code = bun.String.static(err.code()),
.message = bun.String.static(err.label()),
};
defer ip_slice.deinit();
globalThis.throwValue(system_error.toErrorInstance(globalThis));
return .zero;
},

View File

@@ -17,6 +17,7 @@ const uws = @import("root").bun.uws;
const ZigString = JSC.ZigString;
const BoringSSL = bun.BoringSSL;
const X509 = @import("./x509.zig");
const Async = bun.Async;
fn normalizeListeningHost(host: [:0]const u8) ?[*:0]const u8 {
if (host.len == 0 or strings.eqlComptime(host, "0.0.0.0")) {
@@ -447,7 +448,7 @@ pub const Listener = struct {
handlers: Handlers,
listener: ?*uws.ListenSocket = null,
poll_ref: JSC.PollRef = JSC.PollRef.init(),
poll_ref: Async.KeepAlive = Async.KeepAlive.init(),
connection: UnixOrHost,
socket_context: ?*uws.SocketContext = null,
ssl: bool = false,
@@ -582,7 +583,7 @@ pub const Listener = struct {
var socket_context = uws.us_create_bun_socket_context(
@intFromBool(ssl_enabled),
uws.Loop.get().?,
uws.Loop.get(),
@sizeOf(usize),
ctx_opts,
) orelse {
@@ -919,7 +920,7 @@ pub const Listener = struct {
globalObject.bunVM().eventLoop().ensureWaker();
var socket_context = uws.us_create_bun_socket_context(@intFromBool(ssl_enabled), uws.Loop.get().?, @sizeOf(usize), ctx_opts).?;
var socket_context = uws.us_create_bun_socket_context(@intFromBool(ssl_enabled), uws.Loop.get(), @sizeOf(usize), ctx_opts).?;
var connection: Listener.UnixOrHost = if (port) |port_| .{
.host = .{ .host = (hostname_or_unix.cloneIfNeeded(bun.default_allocator) catch unreachable).slice(), .port = port_ },
} else .{
@@ -1077,7 +1078,7 @@ fn NewSocket(comptime ssl: bool) type {
wrapped: WrappedType = .none,
handlers: *Handlers,
this_value: JSC.JSValue = .zero,
poll_ref: JSC.PollRef = JSC.PollRef.init(),
poll_ref: Async.KeepAlive = Async.KeepAlive.init(),
reffer: JSC.Ref = JSC.Ref.init(),
last_4: [4]u8 = .{ 0, 0, 0, 0 },
authorized: bool = false,

View File

@@ -13,8 +13,9 @@ const JSC = @import("root").bun.JSC;
const JSValue = JSC.JSValue;
const JSGlobalObject = JSC.JSGlobalObject;
const Which = @import("../../../which.zig");
const uws = @import("../../../deps/uws.zig");
const Async = bun.Async;
const IPC = @import("../../ipc.zig");
const uws = bun.uws;
pub const Subprocess = struct {
const log = Output.scoped(.Subprocess, false);
@@ -30,7 +31,7 @@ pub const Subprocess = struct {
stdout: Readable,
stderr: Readable,
killed: bool = false,
poll_ref: ?*JSC.FilePoll = null,
poll_ref: ?*Async.FilePoll = null,
exit_promise: JSC.Strong = .{},
on_exit_callback: JSC.Strong = .{},
@@ -470,7 +471,7 @@ pub const Subprocess = struct {
pub const BufferedInput = struct {
remain: []const u8 = "",
fd: bun.FileDescriptor = bun.invalid_fd,
poll_ref: ?*JSC.FilePoll = null,
poll_ref: ?*Async.FilePoll = null,
written: usize = 0,
source: union(enum) {
@@ -1527,7 +1528,7 @@ pub const Subprocess = struct {
const watchfd = if (comptime Environment.isLinux) pidfd else pid;
if (comptime !is_sync) {
var poll = JSC.FilePoll.init(jsc_vm, watchfd, .{}, Subprocess, subprocess);
var poll = Async.FilePoll.init(jsc_vm, watchfd, .{}, Subprocess, subprocess);
subprocess.poll_ref = poll;
switch (subprocess.poll_ref.?.register(
jsc_vm.event_loop_handle.?,
@@ -1590,7 +1591,7 @@ pub const Subprocess = struct {
subprocess.closeIO(.stdin);
{
var poll = JSC.FilePoll.init(jsc_vm, watchfd, .{}, Subprocess, subprocess);
var poll = Async.FilePoll.init(jsc_vm, watchfd, .{}, Subprocess, subprocess);
subprocess.poll_ref = poll;
switch (subprocess.poll_ref.?.register(
jsc_vm.event_loop_handle.?,

View File

@@ -50,7 +50,6 @@ const MarkedArrayBuffer = @import("../base.zig").MarkedArrayBuffer;
const getAllocator = @import("../base.zig").getAllocator;
const JSValue = @import("root").bun.JSC.JSValue;
const Microtask = @import("root").bun.JSC.Microtask;
const JSGlobalObject = @import("root").bun.JSC.JSGlobalObject;
const ExceptionValueRef = @import("root").bun.JSC.ExceptionValueRef;
const JSPrivateDataPtr = @import("root").bun.JSC.JSPrivateDataPtr;
@@ -668,7 +667,9 @@ pub const FFI = struct {
val.arg_types.clearAndFree(allocator);
if (val.state) |state| {
TCC.tcc_delete(state);
if (comptime !Environment.isWindows) {
TCC.tcc_delete(state);
}
val.state = null;
}
@@ -768,6 +769,9 @@ pub const FFI = struct {
this: *Function,
allocator: std.mem.Allocator,
) !void {
if (comptime Environment.isWindows) {
return;
}
var source_code = std.ArrayList(u8).init(allocator);
var source_code_writer = source_code.writer();
try this.printSourceCode(&source_code_writer);
@@ -782,7 +786,9 @@ pub const FFI = struct {
this.state = state;
defer {
if (this.step == .failed) {
TCC.tcc_delete(state);
if (comptime !Environment.isWindows) {
TCC.tcc_delete(state);
}
this.state = null;
}
}
@@ -891,6 +897,9 @@ pub const FFI = struct {
}
pub fn inject(state: *TCC.TCCState) void {
if (comptime Environment.isWindows) {
return;
}
JSC.markBinding(@src());
_ = TCC.tcc_add_symbol(state, "memset", &memset);
_ = TCC.tcc_add_symbol(state, "memcpy", &memcpy);
@@ -931,6 +940,9 @@ pub const FFI = struct {
js_function: JSValue,
is_threadsafe: bool,
) !void {
if (comptime Environment.isWindows) {
return;
}
JSC.markBinding(@src());
var source_code = std.ArrayList(u8).init(allocator);
var source_code_writer = source_code.writer();
@@ -954,7 +966,9 @@ pub const FFI = struct {
this.state = state;
defer {
if (this.step == .failed) {
TCC.tcc_delete(state);
if (comptime !Environment.isWindows) {
TCC.tcc_delete(state);
}
this.state = null;
}
}

View File

@@ -49,7 +49,6 @@ const MarkedArrayBuffer = @import("../base.zig").MarkedArrayBuffer;
const getAllocator = @import("../base.zig").getAllocator;
const JSValue = @import("root").bun.JSC.JSValue;
const Microtask = @import("root").bun.JSC.Microtask;
const JSGlobalObject = @import("root").bun.JSC.JSGlobalObject;
const ExceptionValueRef = @import("root").bun.JSC.ExceptionValueRef;
const JSPrivateDataPtr = @import("root").bun.JSC.JSPrivateDataPtr;
@@ -90,6 +89,7 @@ const SendfileContext = struct {
};
const DateTime = bun.DateTime;
const linux = std.os.linux;
const Async = bun.Async;
const BlobFileContentResult = struct {
data: [:0]const u8,
@@ -4725,7 +4725,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp
listen_callback: JSC.AnyTask = undefined,
allocator: std.mem.Allocator,
poll_ref: JSC.PollRef = .{},
poll_ref: Async.KeepAlive = .{},
temporary_url_buffer: std.ArrayListUnmanaged(u8) = .{},
cached_hostname: bun.String = bun.String.empty,
@@ -5427,7 +5427,7 @@ pub fn NewServer(comptime NamespaceType: type, comptime ssl_enabled_: bool, comp
}
this.listener = socket;
this.vm.event_loop_handle = uws.Loop.get();
this.vm.event_loop_handle = Async.Loop.get();
}
pub fn ref(this: *ThisServer) void {

View File

@@ -1592,839 +1592,6 @@ pub const Ref = struct {
}
};
/// Track if an object whose file descriptor is being watched should keep the event loop alive.
/// This is not reference counted. It only tracks active or inactive.
pub const PollRef = struct {
status: Status = .inactive,
const log = Output.scoped(.PollRef, false);
const Status = enum { active, inactive, done };
pub inline fn isActive(this: PollRef) bool {
return this.status == .active;
}
/// Make calling ref() on this poll into a no-op.
pub fn disable(this: *PollRef) void {
this.unref(JSC.VirtualMachine.get());
this.status = .done;
}
/// Only intended to be used from EventLoop.Pollable
pub fn deactivate(this: *PollRef, loop: *uws.Loop) void {
if (this.status != .active)
return;
this.status = .inactive;
loop.num_polls -= 1;
loop.active -|= 1;
}
/// Only intended to be used from EventLoop.Pollable
pub fn activate(this: *PollRef, loop: *uws.Loop) void {
if (this.status != .inactive)
return;
this.status = .active;
loop.num_polls += 1;
loop.active += 1;
}
pub fn init() PollRef {
return .{};
}
/// Prevent a poll from keeping the process alive.
pub fn unref(this: *PollRef, vm: *JSC.VirtualMachine) void {
if (this.status != .active)
return;
this.status = .inactive;
vm.event_loop_handle.?.unref();
}
/// From another thread, Prevent a poll from keeping the process alive.
pub fn unrefConcurrently(this: *PollRef, vm: *JSC.VirtualMachine) void {
if (this.status != .active)
return;
this.status = .inactive;
vm.event_loop_handle.?.unrefConcurrently();
}
/// Prevent a poll from keeping the process alive on the next tick.
pub fn unrefOnNextTick(this: *PollRef, vm: *JSC.VirtualMachine) void {
if (this.status != .active)
return;
this.status = .inactive;
vm.pending_unref_counter +|= 1;
}
/// From another thread, prevent a poll from keeping the process alive on the next tick.
pub fn unrefOnNextTickConcurrently(this: *PollRef, vm: *JSC.VirtualMachine) void {
if (this.status != .active)
return;
this.status = .inactive;
_ = @atomicRmw(@TypeOf(vm.pending_unref_counter), &vm.pending_unref_counter, .Add, 1, .Monotonic);
}
/// Allow a poll to keep the process alive.
pub fn ref(this: *PollRef, vm: *JSC.VirtualMachine) void {
if (this.status != .inactive)
return;
this.status = .active;
vm.event_loop_handle.?.ref();
}
/// Allow a poll to keep the process alive.
pub fn refConcurrently(this: *PollRef, vm: *JSC.VirtualMachine) void {
if (this.status != .inactive)
return;
this.status = .active;
vm.event_loop_handle.?.refConcurrently();
}
pub fn refConcurrentlyFromEventLoop(this: *PollRef, loop: *JSC.EventLoop) void {
this.refConcurrently(loop.virtual_machine);
}
pub fn unrefConcurrentlyFromEventLoop(this: *PollRef, loop: *JSC.EventLoop) void {
this.unrefConcurrently(loop.virtual_machine);
}
};
const KQueueGenerationNumber = if (Environment.isMac and Environment.allow_assert) usize else u0;
pub const FilePoll = struct {
var max_generation_number: KQueueGenerationNumber = 0;
fd: bun.UFileDescriptor = invalid_fd,
flags: Flags.Set = Flags.Set{},
owner: Owner = undefined,
/// We re-use FilePoll objects to avoid allocating new ones.
///
/// That means we might run into situations where the event is stale.
/// on macOS kevent64 has an extra pointer field so we use it for that
/// linux doesn't have a field like that
generation_number: KQueueGenerationNumber = 0,
next_to_free: ?*FilePoll = null,
const FileReader = JSC.WebCore.FileReader;
const FileSink = JSC.WebCore.FileSink;
const FIFO = JSC.WebCore.FIFO;
const Subprocess = JSC.Subprocess;
const BufferedInput = Subprocess.BufferedInput;
const BufferedOutput = Subprocess.BufferedOutput;
const DNSResolver = JSC.DNS.DNSResolver;
const GetAddrInfoRequest = JSC.DNS.GetAddrInfoRequest;
const Deactivated = opaque {
pub var owner: Owner = Owner.init(@as(*Deactivated, @ptrFromInt(@as(usize, 0xDEADBEEF))));
};
pub const Owner = bun.TaggedPointerUnion(.{
FileReader,
FileSink,
Subprocess,
BufferedInput,
FIFO,
Deactivated,
DNSResolver,
GetAddrInfoRequest,
});
fn updateFlags(poll: *FilePoll, updated: Flags.Set) void {
var flags = poll.flags;
flags.remove(.readable);
flags.remove(.writable);
flags.remove(.process);
flags.remove(.machport);
flags.remove(.eof);
flags.remove(.hup);
flags.setUnion(updated);
poll.flags = flags;
}
pub fn onKQueueEvent(poll: *FilePoll, loop: *uws.Loop, kqueue_event: *const std.os.system.kevent64_s) void {
if (KQueueGenerationNumber != u0)
std.debug.assert(poll.generation_number == kqueue_event.ext[0]);
poll.updateFlags(Flags.fromKQueueEvent(kqueue_event.*));
poll.onUpdate(loop, kqueue_event.data);
}
pub fn onEpollEvent(poll: *FilePoll, loop: *uws.Loop, epoll_event: *std.os.linux.epoll_event) void {
poll.updateFlags(Flags.fromEpollEvent(epoll_event.*));
poll.onUpdate(loop, 0);
}
pub fn clearEvent(poll: *FilePoll, flag: Flags) void {
poll.flags.remove(flag);
}
pub fn isReadable(this: *FilePoll) bool {
const readable = this.flags.contains(.readable);
this.flags.remove(.readable);
return readable;
}
pub fn isHUP(this: *FilePoll) bool {
const readable = this.flags.contains(.hup);
this.flags.remove(.hup);
return readable;
}
pub fn isEOF(this: *FilePoll) bool {
const readable = this.flags.contains(.eof);
this.flags.remove(.eof);
return readable;
}
pub fn isWritable(this: *FilePoll) bool {
const readable = this.flags.contains(.writable);
this.flags.remove(.writable);
return readable;
}
pub fn deinit(this: *FilePoll) void {
var vm = JSC.VirtualMachine.get();
this.deinitWithVM(vm);
}
fn deinitPossiblyDefer(this: *FilePoll, vm: *JSC.VirtualMachine, loop: *uws.Loop, polls: *JSC.FilePoll.Store) void {
if (this.isRegistered()) {
_ = this.unregister(loop);
}
this.owner = Deactivated.owner;
const was_ever_registered = this.flags.contains(.was_ever_registered);
this.flags = Flags.Set{};
this.fd = invalid_fd;
polls.put(this, vm, was_ever_registered);
}
pub fn deinitWithVM(this: *FilePoll, vm: *JSC.VirtualMachine) void {
var loop = vm.event_loop_handle.?;
this.deinitPossiblyDefer(vm, loop, vm.rareData().filePolls(vm));
}
pub fn isRegistered(this: *const FilePoll) bool {
return this.flags.contains(.poll_writable) or this.flags.contains(.poll_readable) or this.flags.contains(.poll_process) or this.flags.contains(.poll_machport);
}
const kqueue_or_epoll = if (Environment.isMac) "kevent" else "epoll";
pub fn onUpdate(poll: *FilePoll, loop: *uws.Loop, size_or_offset: i64) void {
if (poll.flags.contains(.one_shot) and !poll.flags.contains(.needs_rearm)) {
if (poll.flags.contains(.has_incremented_poll_count)) poll.deactivate(loop);
poll.flags.insert(.needs_rearm);
}
var ptr = poll.owner;
switch (ptr.tag()) {
@field(Owner.Tag, "FIFO") => {
log("onUpdate " ++ kqueue_or_epoll ++ " (fd: {d}) FIFO", .{poll.fd});
ptr.as(FIFO).ready(size_or_offset, poll.flags.contains(.hup));
},
@field(Owner.Tag, "Subprocess") => {
log("onUpdate " ++ kqueue_or_epoll ++ " (fd: {d}) Subprocess", .{poll.fd});
var loader = ptr.as(JSC.Subprocess);
loader.onExitNotification();
},
@field(Owner.Tag, "FileSink") => {
log("onUpdate " ++ kqueue_or_epoll ++ " (fd: {d}) FileSink", .{poll.fd});
var loader = ptr.as(JSC.WebCore.FileSink);
loader.onPoll(size_or_offset, 0);
},
@field(Owner.Tag, "DNSResolver") => {
log("onUpdate " ++ kqueue_or_epoll ++ " (fd: {d}) DNSResolver", .{poll.fd});
var loader: *DNSResolver = ptr.as(DNSResolver);
loader.onDNSPoll(poll);
},
@field(Owner.Tag, "GetAddrInfoRequest") => {
log("onUpdate " ++ kqueue_or_epoll ++ " (fd: {d}) GetAddrInfoRequest", .{poll.fd});
var loader: *GetAddrInfoRequest = ptr.as(GetAddrInfoRequest);
loader.onMachportChange();
},
else => {
log("onUpdate " ++ kqueue_or_epoll ++ " (fd: {d}) disconnected?", .{poll.fd});
},
}
}
pub const Flags = enum {
// What are we asking the event loop about?
/// Poll for readable events
poll_readable,
/// Poll for writable events
poll_writable,
/// Poll for process-related events
poll_process,
/// Poll for machport events
poll_machport,
// What did the event loop tell us?
readable,
writable,
process,
eof,
hup,
machport,
// What is the type of file descriptor?
fifo,
tty,
one_shot,
needs_rearm,
has_incremented_poll_count,
disable,
nonblocking,
was_ever_registered,
ignore_updates,
pub fn poll(this: Flags) Flags {
return switch (this) {
.readable => .poll_readable,
.writable => .poll_writable,
.process => .poll_process,
.machport => .poll_machport,
else => this,
};
}
pub const Set = std.EnumSet(Flags);
pub const Struct = std.enums.EnumFieldStruct(Flags, bool, false);
pub fn fromKQueueEvent(kqueue_event: std.os.system.kevent64_s) Flags.Set {
var flags = Flags.Set{};
if (kqueue_event.filter == std.os.system.EVFILT_READ) {
flags.insert(Flags.readable);
log("readable", .{});
if (kqueue_event.flags & std.os.system.EV_EOF != 0) {
flags.insert(Flags.hup);
log("hup", .{});
}
} else if (kqueue_event.filter == std.os.system.EVFILT_WRITE) {
flags.insert(Flags.writable);
log("writable", .{});
if (kqueue_event.flags & std.os.system.EV_EOF != 0) {
flags.insert(Flags.hup);
log("hup", .{});
}
} else if (kqueue_event.filter == std.os.system.EVFILT_PROC) {
log("proc", .{});
flags.insert(Flags.process);
} else if (kqueue_event.filter == std.os.system.EVFILT_MACHPORT) {
log("machport", .{});
flags.insert(Flags.machport);
}
return flags;
}
pub fn fromEpollEvent(epoll: std.os.linux.epoll_event) Flags.Set {
var flags = Flags.Set{};
if (epoll.events & std.os.linux.EPOLL.IN != 0) {
flags.insert(Flags.readable);
log("readable", .{});
}
if (epoll.events & std.os.linux.EPOLL.OUT != 0) {
flags.insert(Flags.writable);
log("writable", .{});
}
if (epoll.events & std.os.linux.EPOLL.ERR != 0) {
flags.insert(Flags.eof);
log("eof", .{});
}
if (epoll.events & std.os.linux.EPOLL.HUP != 0) {
flags.insert(Flags.hup);
log("hup", .{});
}
return flags;
}
};
const HiveArray = bun.HiveArray(FilePoll, 128).Fallback;
// We defer freeing FilePoll until the end of the next event loop iteration
// This ensures that we don't free a FilePoll before the next callback is called
pub const Store = struct {
hive: HiveArray,
pending_free_head: ?*FilePoll = null,
pending_free_tail: ?*FilePoll = null,
const log = Output.scoped(.FilePoll, false);
pub fn init(allocator: std.mem.Allocator) Store {
return .{
.hive = HiveArray.init(allocator),
};
}
pub fn get(this: *Store) *FilePoll {
return this.hive.get();
}
pub fn processDeferredFrees(this: *Store) void {
var next = this.pending_free_head;
while (next) |current| {
next = current.next_to_free;
current.next_to_free = null;
this.hive.put(current);
}
this.pending_free_head = null;
this.pending_free_tail = null;
}
pub fn put(this: *Store, poll: *FilePoll, vm: *JSC.VirtualMachine, ever_registered: bool) void {
if (!ever_registered) {
this.hive.put(poll);
return;
}
std.debug.assert(poll.next_to_free == null);
if (this.pending_free_tail) |tail| {
std.debug.assert(this.pending_free_head != null);
std.debug.assert(tail.next_to_free == null);
tail.next_to_free = poll;
}
if (this.pending_free_head == null) {
this.pending_free_head = poll;
std.debug.assert(this.pending_free_tail == null);
}
poll.flags.insert(.ignore_updates);
this.pending_free_tail = poll;
std.debug.assert(vm.after_event_loop_callback == null or vm.after_event_loop_callback == @as(?JSC.OpaqueCallback, @ptrCast(&processDeferredFrees)));
vm.after_event_loop_callback = @ptrCast(&processDeferredFrees);
vm.after_event_loop_callback_ctx = this;
}
};
const log = Output.scoped(.FilePoll, false);
pub inline fn isActive(this: *const FilePoll) bool {
return this.flags.contains(.has_incremented_poll_count);
}
pub inline fn isWatching(this: *const FilePoll) bool {
return !this.flags.contains(.needs_rearm) and (this.flags.contains(.poll_readable) or this.flags.contains(.poll_writable) or this.flags.contains(.poll_process));
}
pub inline fn isKeepingProcessAlive(this: *const FilePoll) bool {
return !this.flags.contains(.disable) and this.isActive();
}
/// Make calling ref() on this poll into a no-op.
pub fn disableKeepingProcessAlive(this: *FilePoll, vm: *JSC.VirtualMachine) void {
if (this.flags.contains(.disable))
return;
this.flags.insert(.disable);
vm.event_loop_handle.?.active -= @as(u32, @intFromBool(this.flags.contains(.has_incremented_poll_count)));
}
pub fn enableKeepingProcessAlive(this: *FilePoll, vm: *JSC.VirtualMachine) void {
if (!this.flags.contains(.disable))
return;
this.flags.remove(.disable);
vm.event_loop_handle.?.active += @as(u32, @intFromBool(this.flags.contains(.has_incremented_poll_count)));
}
pub fn canActivate(this: *const FilePoll) bool {
return !this.flags.contains(.has_incremented_poll_count);
}
/// Only intended to be used from EventLoop.Pollable
pub fn deactivate(this: *FilePoll, loop: *uws.Loop) void {
std.debug.assert(this.flags.contains(.has_incremented_poll_count));
loop.num_polls -= @as(i32, @intFromBool(this.flags.contains(.has_incremented_poll_count)));
loop.active -|= @as(u32, @intFromBool(!this.flags.contains(.disable) and this.flags.contains(.has_incremented_poll_count)));
this.flags.remove(.has_incremented_poll_count);
}
/// Only intended to be used from EventLoop.Pollable
pub fn activate(this: *FilePoll, loop: *uws.Loop) void {
loop.num_polls += @as(i32, @intFromBool(!this.flags.contains(.has_incremented_poll_count)));
loop.active += @as(u32, @intFromBool(!this.flags.contains(.disable) and !this.flags.contains(.has_incremented_poll_count)));
this.flags.insert(.has_incremented_poll_count);
}
pub fn init(vm: *JSC.VirtualMachine, fd: bun.FileDescriptor, flags: Flags.Struct, comptime Type: type, owner: *Type) *FilePoll {
return initWithOwner(vm, fd, flags, Owner.init(owner));
}
pub fn initWithOwner(vm: *JSC.VirtualMachine, fd: bun.FileDescriptor, flags: Flags.Struct, owner: Owner) *FilePoll {
var poll = vm.rareData().filePolls(vm).get();
poll.fd = @intCast(fd);
poll.flags = Flags.Set.init(flags);
poll.owner = owner;
poll.next_to_free = null;
if (KQueueGenerationNumber != u0) {
max_generation_number +%= 1;
poll.generation_number = max_generation_number;
}
return poll;
}
pub inline fn canRef(this: *const FilePoll) bool {
if (this.flags.contains(.disable))
return false;
return !this.flags.contains(.has_incremented_poll_count);
}
pub inline fn canUnref(this: *const FilePoll) bool {
return this.flags.contains(.has_incremented_poll_count);
}
/// Prevent a poll from keeping the process alive.
pub fn unref(this: *FilePoll, vm: *JSC.VirtualMachine) void {
if (!this.canUnref())
return;
log("unref", .{});
this.deactivate(vm.event_loop_handle.?);
}
/// Allow a poll to keep the process alive.
pub fn ref(this: *FilePoll, vm: *JSC.VirtualMachine) void {
if (this.canRef())
return;
log("ref", .{});
this.activate(vm.event_loop_handle.?);
}
pub fn onTick(loop: *uws.Loop, tagged_pointer: ?*anyopaque) callconv(.C) void {
var tag = Pollable.from(tagged_pointer);
if (tag.tag() != @field(Pollable.Tag, "FilePoll"))
return;
var file_poll: *FilePoll = tag.as(FilePoll);
if (file_poll.flags.contains(.ignore_updates)) {
return;
}
if (comptime Environment.isMac)
onKQueueEvent(file_poll, loop, &loop.ready_polls[@as(usize, @intCast(loop.current_ready_poll))])
else if (comptime Environment.isLinux)
onEpollEvent(file_poll, loop, &loop.ready_polls[@as(usize, @intCast(loop.current_ready_poll))]);
}
const Pollable = bun.TaggedPointerUnion(
.{
FilePoll,
Deactivated,
},
);
comptime {
@export(onTick, .{ .name = "Bun__internal_dispatch_ready_poll" });
}
const timeout = std.mem.zeroes(std.os.timespec);
const kevent = std.c.kevent;
const linux = std.os.linux;
pub fn register(this: *FilePoll, loop: *uws.Loop, flag: Flags, one_shot: bool) JSC.Maybe(void) {
return registerWithFd(this, loop, flag, one_shot, this.fd);
}
pub fn registerWithFd(this: *FilePoll, loop: *uws.Loop, flag: Flags, one_shot: bool, fd: u64) JSC.Maybe(void) {
const watcher_fd = loop.fd;
log("register: {s} ({d})", .{ @tagName(flag), fd });
std.debug.assert(fd != invalid_fd);
if (one_shot) {
this.flags.insert(.one_shot);
}
if (comptime Environment.isLinux) {
const one_shot_flag: u32 = if (!this.flags.contains(.one_shot)) 0 else linux.EPOLL.ONESHOT;
const flags: u32 = switch (flag) {
.process,
.readable,
=> linux.EPOLL.IN | linux.EPOLL.HUP | one_shot_flag,
.writable => linux.EPOLL.OUT | linux.EPOLL.HUP | linux.EPOLL.ERR | one_shot_flag,
else => unreachable,
};
var event = linux.epoll_event{ .events = flags, .data = .{ .u64 = @intFromPtr(Pollable.init(this).ptr()) } };
const ctl = linux.epoll_ctl(
watcher_fd,
if (this.isRegistered() or this.flags.contains(.needs_rearm)) linux.EPOLL.CTL_MOD else linux.EPOLL.CTL_ADD,
@as(std.os.fd_t, @intCast(fd)),
&event,
);
this.flags.insert(.was_ever_registered);
if (JSC.Maybe(void).errnoSys(ctl, .epoll_ctl)) |errno| {
return errno;
}
} else if (comptime Environment.isMac) {
var changelist = std.mem.zeroes([2]std.os.system.kevent64_s);
const one_shot_flag: u16 = if (!this.flags.contains(.one_shot)) 0 else std.c.EV_ONESHOT;
changelist[0] = switch (flag) {
.readable => .{
.ident = @as(u64, @intCast(fd)),
.filter = std.os.system.EVFILT_READ,
.data = 0,
.fflags = 0,
.udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_ADD | one_shot_flag,
.ext = .{ this.generation_number, 0 },
},
.writable => .{
.ident = @as(u64, @intCast(fd)),
.filter = std.os.system.EVFILT_WRITE,
.data = 0,
.fflags = 0,
.udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_ADD | one_shot_flag,
.ext = .{ this.generation_number, 0 },
},
.process => .{
.ident = @as(u64, @intCast(fd)),
.filter = std.os.system.EVFILT_PROC,
.data = 0,
.fflags = std.c.NOTE_EXIT,
.udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_ADD | one_shot_flag,
.ext = .{ this.generation_number, 0 },
},
.machport => .{
.ident = @as(u64, @intCast(fd)),
.filter = std.os.system.EVFILT_MACHPORT,
.data = 0,
.fflags = 0,
.udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_ADD | one_shot_flag,
.ext = .{ this.generation_number, 0 },
},
else => unreachable,
};
// output events only include change errors
const KEVENT_FLAG_ERROR_EVENTS = 0x000002;
// The kevent() system call returns the number of events placed in
// the eventlist, up to the value given by nevents. If the time
// limit expires, then kevent() returns 0.
const rc = rc: {
while (true) {
const rc = std.os.system.kevent64(
watcher_fd,
&changelist,
1,
// The same array may be used for the changelist and eventlist.
&changelist,
// we set 0 here so that if we get an error on
// registration, it becomes errno
0,
KEVENT_FLAG_ERROR_EVENTS,
&timeout,
);
if (std.c.getErrno(rc) == .INTR) continue;
break :rc rc;
}
};
this.flags.insert(.was_ever_registered);
// If an error occurs while
// processing an element of the changelist and there is enough room
// in the eventlist, then the event will be placed in the eventlist
// with EV_ERROR set in flags and the system error in data.
if (changelist[0].flags == std.c.EV_ERROR and changelist[0].data != 0) {
return JSC.Maybe(void).errnoSys(changelist[0].data, .kevent).?;
// Otherwise, -1 will be returned, and errno will be set to
// indicate the error condition.
}
const errno = std.c.getErrno(rc);
if (errno != .SUCCESS) {
return JSC.Maybe(void){
.err = bun.sys.Error.fromCode(errno, .kqueue),
};
}
} else {
bun.todo(@src(), {});
}
if (this.canActivate())
this.activate(loop);
this.flags.insert(switch (flag) {
.readable => .poll_readable,
.process => if (comptime Environment.isLinux) .poll_readable else .poll_process,
.writable => .poll_writable,
.machport => .poll_machport,
else => unreachable,
});
this.flags.remove(.needs_rearm);
return JSC.Maybe(void).success;
}
const invalid_fd = bun.invalid_fd;
pub fn unregister(this: *FilePoll, loop: *uws.Loop) JSC.Maybe(void) {
return this.unregisterWithFd(loop, this.fd);
}
pub fn unregisterWithFd(this: *FilePoll, loop: *uws.Loop, fd: bun.UFileDescriptor) JSC.Maybe(void) {
if (!(this.flags.contains(.poll_readable) or this.flags.contains(.poll_writable) or this.flags.contains(.poll_process) or this.flags.contains(.poll_machport))) {
// no-op
return JSC.Maybe(void).success;
}
std.debug.assert(fd != invalid_fd);
const watcher_fd = loop.fd;
const flag: Flags = brk: {
if (this.flags.contains(.poll_readable))
break :brk .readable;
if (this.flags.contains(.poll_writable))
break :brk .writable;
if (this.flags.contains(.poll_process))
break :brk .process;
if (this.flags.contains(.poll_machport))
break :brk .machport;
return JSC.Maybe(void).success;
};
if (this.flags.contains(.needs_rearm)) {
log("unregister: {s} ({d}) skipped due to needs_rearm", .{ @tagName(flag), fd });
this.flags.remove(.poll_process);
this.flags.remove(.poll_readable);
this.flags.remove(.poll_process);
this.flags.remove(.poll_machport);
return JSC.Maybe(void).success;
}
log("unregister: {s} ({d})", .{ @tagName(flag), fd });
if (comptime Environment.isLinux) {
const ctl = linux.epoll_ctl(
watcher_fd,
linux.EPOLL.CTL_DEL,
@as(std.os.fd_t, @intCast(fd)),
null,
);
if (JSC.Maybe(void).errnoSys(ctl, .epoll_ctl)) |errno| {
return errno;
}
} else if (comptime Environment.isMac) {
var changelist = std.mem.zeroes([2]std.os.system.kevent64_s);
changelist[0] = switch (flag) {
.readable => .{
.ident = @as(u64, @intCast(fd)),
.filter = std.os.system.EVFILT_READ,
.data = 0,
.fflags = 0,
.udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_DELETE,
.ext = .{ 0, 0 },
},
.machport => .{
.ident = @as(u64, @intCast(fd)),
.filter = std.os.system.EVFILT_MACHPORT,
.data = 0,
.fflags = 0,
.udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_DELETE,
.ext = .{ 0, 0 },
},
.writable => .{
.ident = @as(u64, @intCast(fd)),
.filter = std.os.system.EVFILT_WRITE,
.data = 0,
.fflags = 0,
.udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_DELETE,
.ext = .{ 0, 0 },
},
.process => .{
.ident = @as(u64, @intCast(fd)),
.filter = std.os.system.EVFILT_PROC,
.data = 0,
.fflags = std.c.NOTE_EXIT,
.udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_DELETE,
.ext = .{ 0, 0 },
},
else => unreachable,
};
// output events only include change errors
const KEVENT_FLAG_ERROR_EVENTS = 0x000002;
// The kevent() system call returns the number of events placed in
// the eventlist, up to the value given by nevents. If the time
// limit expires, then kevent() returns 0.
const rc = std.os.system.kevent64(
watcher_fd,
&changelist,
1,
// The same array may be used for the changelist and eventlist.
&changelist,
1,
KEVENT_FLAG_ERROR_EVENTS,
&timeout,
);
// If an error occurs while
// processing an element of the changelist and there is enough room
// in the eventlist, then the event will be placed in the eventlist
// with EV_ERROR set in flags and the system error in data.
if (changelist[0].flags == std.c.EV_ERROR) {
return JSC.Maybe(void).errnoSys(changelist[0].data, .kevent).?;
// Otherwise, -1 will be returned, and errno will be set to
// indicate the error condition.
}
const errno = std.c.getErrno(rc);
switch (rc) {
std.math.minInt(@TypeOf(rc))...-1 => return JSC.Maybe(void).errnoSys(@intFromEnum(errno), .kevent).?,
else => {},
}
} else {
bun.todo(@src(), {});
}
this.flags.remove(.needs_rearm);
this.flags.remove(.one_shot);
// we don't support both right now
std.debug.assert(!(this.flags.contains(.poll_readable) and this.flags.contains(.poll_writable)));
this.flags.remove(.poll_readable);
this.flags.remove(.poll_writable);
this.flags.remove(.poll_process);
this.flags.remove(.poll_machport);
if (this.isActive())
this.deactivate(loop);
return JSC.Maybe(void).success;
}
};
pub const Strong = @import("./Strong.zig").Strong;
pub const BinaryType = enum {

View File

@@ -28,7 +28,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "webcore/config.h"
#include "ActiveDOMCallback.h"
#include "ScriptExecutionContext.h"

View File

@@ -1,9 +1,7 @@
#pragma once
#include "root.h"
#include "ZigGlobalObject.h"
#include "AsyncContextFrame.h"
#include "JavaScriptCore/InternalFieldTuple.h"
#include <JavaScriptCore/InternalFieldTuple.h>
using namespace JSC;
using namespace WebCore;
@@ -64,7 +62,7 @@ void AsyncContextFrame::visitChildrenImpl(JSCell* cell, Visitor& visitor)
DEFINE_VISIT_CHILDREN(AsyncContextFrame);
extern "C" EncodedJSValue AsyncContextFrame__withAsyncContextIfNeeded(JSGlobalObject* globalObject, EncodedJSValue callback)
extern "C" JSC::EncodedJSValue AsyncContextFrame__withAsyncContextIfNeeded(JSGlobalObject* globalObject, JSC::EncodedJSValue callback)
{
return JSValue::encode(AsyncContextFrame::withAsyncContextIfNeeded(globalObject, JSValue::decode(callback)));
}

View File

@@ -2,7 +2,7 @@
#include "root.h"
#include "BunClientData.h"
#include "JavaScriptCore/CallData.h"
#include <JavaScriptCore/CallData.h>
class AsyncContextFrame : public JSC::JSNonFinalObject {
public:

View File

@@ -7,7 +7,7 @@
#include "root.h"
#include "Buffer.h"
#include "JavaScriptCore/Uint8Array.h"
#include <JavaScriptCore/Uint8Array.h>
namespace WebCore {
@@ -22,10 +22,12 @@ Ref<Buffer> Buffer::create(JSC::JSGlobalObject* globalObject, JSC::JSUint8Array*
int32_t static write(WTF::StringView view, size_t offset, size_t length, BufferEncodingType encodingType)
{
RELEASE_ASSERT_NOT_REACHED();
}
Buffer::~Buffer()
{
RELEASE_ASSERT_NOT_REACHED();
}
Ref<Buffer> Buffer::createEmpty(JSC::JSGlobalObject* globalObject)
@@ -34,18 +36,20 @@ Ref<Buffer> Buffer::createEmpty(JSC::JSGlobalObject* globalObject)
}
Ref<Buffer> Buffer::create(JSC::JSGlobalObject* globalObject, UChar* ptr, size_t len, BufferEncodingType encoding)
{
RELEASE_ASSERT_NOT_REACHED();
}
Ref<Buffer> Buffer::create(JSC::JSGlobalObject* globalObject, LChar* ptr, size_t len, BufferEncodingType encoding)
{
RELEASE_ASSERT_NOT_REACHED();
}
Ref<Buffer> Buffer::create(JSC::JSGlobalObject* globalObject, WTF::StringView& str, BufferEncodingType encoding)
{
if (str.is8Bit()) {
}
RELEASE_ASSERT_NOT_REACHED();
}
Ref<Buffer> Buffer::create(JSC::JSGlobalObject* globalObject, WTF::String& str, BufferEncodingType encoding)
{
RELEASE_ASSERT_NOT_REACHED();
}
}

View File

@@ -8,8 +8,8 @@
#include "root.h"
#include "BufferEncodingType.h"
#include "JavaScriptCore/GenericTypedArrayView.h"
#include "JavaScriptCore/JSBase.h"
#include <JavaScriptCore/GenericTypedArrayView.h>
#include <JavaScriptCore/JSBase.h>
#include "headers-handwritten.h"
extern "C" JSC::EncodedJSValue JSBuffer__bufferFromLength(JSC::JSGlobalObject* lexicalGlobalObject, int64_t length);

View File

@@ -4,21 +4,21 @@
#include "ExtendedDOMClientIsoSubspaces.h"
#include "ExtendedDOMIsoSubspaces.h"
#include "JavaScriptCore/FastMallocAlignedMemoryAllocator.h"
#include "JavaScriptCore/HeapInlines.h"
#include "JavaScriptCore/IsoHeapCellType.h"
#include "JavaScriptCore/JSDestructibleObjectHeapCellType.h"
// #include "JavaScriptCore/MarkingConstraint.h"
#include "JavaScriptCore/SubspaceInlines.h"
#include "JavaScriptCore/VM.h"
#include "wtf/MainThread.h"
#include <JavaScriptCore/FastMallocAlignedMemoryAllocator.h>
#include <JavaScriptCore/HeapInlines.h>
#include <JavaScriptCore/IsoHeapCellType.h>
#include <JavaScriptCore/JSDestructibleObjectHeapCellType.h>
// #include <JavaScriptCore/MarkingConstraint.h>
#include <JavaScriptCore/SubspaceInlines.h>
#include <JavaScriptCore/VM.h>
#include <wtf/MainThread.h>
#include "JSDOMConstructorBase.h"
#include "JSDOMBuiltinConstructorBase.h"
#include "BunGCOutputConstraint.h"
#include "WebCoreTypedArrayController.h"
#include "JavaScriptCore/JSCInlines.h"
#include <JavaScriptCore/JSCInlines.h>
#include "JSDOMWrapper.h"
#include <JavaScriptCore/DeferredWorkTimer.h>

View File

@@ -17,12 +17,12 @@ class DOMWrapperWorld;
#include "BunBuiltinNames.h"
// #include "WebCoreJSBuiltins.h"
// #include "WorkerThreadType.h"
#include "wtf/Function.h"
#include "wtf/HashSet.h"
#include "wtf/RefPtr.h"
#include "JavaScriptCore/WeakInlines.h"
#include "JavaScriptCore/IsoSubspacePerVM.h"
#include "wtf/StdLibExtras.h"
#include <wtf/Function.h>
#include <wtf/HashSet.h>
#include <wtf/RefPtr.h>
#include <JavaScriptCore/WeakInlines.h>
#include <JavaScriptCore/IsoSubspacePerVM.h>
#include <wtf/StdLibExtras.h>
#include "WebCoreJSBuiltins.h"
#include "JSCTaskScheduler.h"

View File

@@ -25,11 +25,11 @@
#include "config.h"
#include "JavaScriptCore/WeakInlines.h"
#include "JavaScriptCore/AbstractSlotVisitorInlines.h"
#include <JavaScriptCore/WeakInlines.h>
#include <JavaScriptCore/AbstractSlotVisitorInlines.h>
#include "JavaScriptCore/VM.h"
#include "JavaScriptCore/MarkingConstraint.h"
#include <JavaScriptCore/VM.h>
#include <JavaScriptCore/MarkingConstraint.h>
// namespace JSC {
@@ -134,10 +134,10 @@
#include "BunGCOutputConstraint.h"
#include "WebCoreJSClientData.h"
#include "JavaScriptCore/BlockDirectoryInlines.h"
#include "JavaScriptCore/HeapInlines.h"
#include "JavaScriptCore/MarkedBlockInlines.h"
#include "JavaScriptCore/SubspaceInlines.h"
#include <JavaScriptCore/BlockDirectoryInlines.h>
#include <JavaScriptCore/HeapInlines.h>
#include <JavaScriptCore/MarkedBlockInlines.h>
#include <JavaScriptCore/SubspaceInlines.h>
namespace WebCore {

View File

@@ -8,7 +8,7 @@
#include "JSEventListener.h"
#include "JSEventTarget.h"
#include "JSWorker.h"
#include "JavaScriptCore/ObjectConstructor.h"
#include <JavaScriptCore/ObjectConstructor.h>
#include "JSFetchHeaders.h"
#include "JSURLSearchParams.h"

View File

@@ -5,9 +5,9 @@
#include "helpers.h"
#include "IDLTypes.h"
#include "DOMURL.h"
#include "JavaScriptCore/JSPromise.h"
#include "JavaScriptCore/JSBase.h"
#include "JavaScriptCore/BuiltinNames.h"
#include <JavaScriptCore/JSPromise.h>
#include <JavaScriptCore/JSBase.h>
#include <JavaScriptCore/BuiltinNames.h>
#include "ScriptExecutionContext.h"
#include "WebCoreJSClientData.h"
#include <JavaScriptCore/JSFunction.h>
@@ -20,7 +20,7 @@
#include "headers.h"
#include "BunObject.h"
#include "WebCoreJSBuiltins.h"
#include "JavaScriptCore/JSObject.h"
#include <JavaScriptCore/JSObject.h>
#include "DOMJITIDLConvert.h"
#include "DOMJITIDLType.h"
#include "DOMJITIDLTypeFilter.h"
@@ -46,7 +46,7 @@ static JSValue constructEnvObject(VM& vm, JSObject* object)
return jsCast<Zig::GlobalObject*>(object->globalObject())->processEnvObject();
}
static inline EncodedJSValue flattenArrayOfBuffersIntoArrayBuffer(JSGlobalObject* lexicalGlobalObject, JSValue arrayValue)
static inline JSC::EncodedJSValue flattenArrayOfBuffersIntoArrayBuffer(JSGlobalObject* lexicalGlobalObject, JSValue arrayValue)
{
auto& vm = lexicalGlobalObject->vm();
@@ -195,26 +195,26 @@ static JSValue constructPluginObject(VM& vm, JSObject* bunObject)
return pluginFunction;
}
extern "C" EncodedJSValue JSPasswordObject__create(JSGlobalObject*);
extern "C" JSC::EncodedJSValue JSPasswordObject__create(JSGlobalObject*);
static JSValue constructPasswordObject(VM& vm, JSObject* bunObject)
{
return JSValue::decode(JSPasswordObject__create(bunObject->globalObject()));
}
extern "C" EncodedJSValue Bun__DNSResolver__lookup(JSGlobalObject*, JSC::CallFrame*);
extern "C" EncodedJSValue Bun__DNSResolver__resolve(JSGlobalObject*, JSC::CallFrame*);
extern "C" EncodedJSValue Bun__DNSResolver__resolveSrv(JSGlobalObject*, JSC::CallFrame*);
extern "C" EncodedJSValue Bun__DNSResolver__resolveTxt(JSGlobalObject*, JSC::CallFrame*);
extern "C" EncodedJSValue Bun__DNSResolver__resolveSoa(JSGlobalObject*, JSC::CallFrame*);
extern "C" EncodedJSValue Bun__DNSResolver__resolveNaptr(JSGlobalObject*, JSC::CallFrame*);
extern "C" EncodedJSValue Bun__DNSResolver__resolveMx(JSGlobalObject*, JSC::CallFrame*);
extern "C" EncodedJSValue Bun__DNSResolver__resolveCaa(JSGlobalObject*, JSC::CallFrame*);
extern "C" EncodedJSValue Bun__DNSResolver__resolveNs(JSGlobalObject*, JSC::CallFrame*);
extern "C" EncodedJSValue Bun__DNSResolver__resolvePtr(JSGlobalObject*, JSC::CallFrame*);
extern "C" EncodedJSValue Bun__DNSResolver__resolveCname(JSGlobalObject*, JSC::CallFrame*);
extern "C" EncodedJSValue Bun__DNSResolver__getServers(JSGlobalObject*, JSC::CallFrame*);
extern "C" EncodedJSValue Bun__DNSResolver__reverse(JSGlobalObject*, JSC::CallFrame*);
extern "C" JSC::EncodedJSValue Bun__DNSResolver__lookup(JSGlobalObject*, JSC::CallFrame*);
extern "C" JSC::EncodedJSValue Bun__DNSResolver__resolve(JSGlobalObject*, JSC::CallFrame*);
extern "C" JSC::EncodedJSValue Bun__DNSResolver__resolveSrv(JSGlobalObject*, JSC::CallFrame*);
extern "C" JSC::EncodedJSValue Bun__DNSResolver__resolveTxt(JSGlobalObject*, JSC::CallFrame*);
extern "C" JSC::EncodedJSValue Bun__DNSResolver__resolveSoa(JSGlobalObject*, JSC::CallFrame*);
extern "C" JSC::EncodedJSValue Bun__DNSResolver__resolveNaptr(JSGlobalObject*, JSC::CallFrame*);
extern "C" JSC::EncodedJSValue Bun__DNSResolver__resolveMx(JSGlobalObject*, JSC::CallFrame*);
extern "C" JSC::EncodedJSValue Bun__DNSResolver__resolveCaa(JSGlobalObject*, JSC::CallFrame*);
extern "C" JSC::EncodedJSValue Bun__DNSResolver__resolveNs(JSGlobalObject*, JSC::CallFrame*);
extern "C" JSC::EncodedJSValue Bun__DNSResolver__resolvePtr(JSGlobalObject*, JSC::CallFrame*);
extern "C" JSC::EncodedJSValue Bun__DNSResolver__resolveCname(JSGlobalObject*, JSC::CallFrame*);
extern "C" JSC::EncodedJSValue Bun__DNSResolver__getServers(JSGlobalObject*, JSC::CallFrame*);
extern "C" JSC::EncodedJSValue Bun__DNSResolver__reverse(JSGlobalObject*, JSC::CallFrame*);
static JSValue constructDNSObject(VM& vm, JSObject* bunObject)
{
@@ -387,8 +387,8 @@ JSC_DEFINE_HOST_FUNCTION(functionBunSleep,
return JSC::JSValue::encode(promise);
}
extern "C" EncodedJSValue Bun__escapeHTML8(JSGlobalObject* globalObject, EncodedJSValue input, const LChar* ptr, size_t length);
extern "C" EncodedJSValue Bun__escapeHTML16(JSGlobalObject* globalObject, EncodedJSValue input, const UChar* ptr, size_t length);
extern "C" JSC::EncodedJSValue Bun__escapeHTML8(JSGlobalObject* globalObject, JSC::EncodedJSValue input, const LChar* ptr, size_t length);
extern "C" JSC::EncodedJSValue Bun__escapeHTML16(JSGlobalObject* globalObject, JSC::EncodedJSValue input, const UChar* ptr, size_t length);
// JSC_DEFINE_JIT_OPERATION(functionBunEscapeHTMLWithoutTypeCheck, JSC::EncodedJSValue, (JSC::JSGlobalObject * lexicalGlobalObject, JSObject* castedglobalObject, JSString* string))
// {
@@ -426,7 +426,7 @@ JSC_DEFINE_HOST_FUNCTION(functionBunEscapeHTML, (JSC::JSGlobalObject * lexicalGl
RELEASE_AND_RETURN(scope, JSValue::encode(string));
auto resolvedString = string->value(lexicalGlobalObject);
EncodedJSValue encodedInput = JSValue::encode(string);
JSC::EncodedJSValue encodedInput = JSValue::encode(string);
if (!resolvedString.is8Bit()) {
RELEASE_AND_RETURN(scope, Bun__escapeHTML16(lexicalGlobalObject, encodedInput, resolvedString.characters16(), length));
} else {

View File

@@ -1,24 +1,24 @@
#include "BunPlugin.h"
#include "headers-handwritten.h"
#include "JavaScriptCore/CatchScope.h"
#include "JavaScriptCore/JSGlobalObject.h"
#include "JavaScriptCore/JSTypeInfo.h"
#include "JavaScriptCore/Structure.h"
#include <JavaScriptCore/CatchScope.h>
#include <JavaScriptCore/JSGlobalObject.h>
#include <JavaScriptCore/JSTypeInfo.h>
#include <JavaScriptCore/Structure.h>
#include "helpers.h"
#include "ZigGlobalObject.h"
#include "JavaScriptCore/JavaScript.h"
#include "JavaScriptCore/JSObjectInlines.h"
#include "wtf/text/WTFString.h"
#include "JavaScriptCore/JSCInlines.h"
#include <JavaScriptCore/JavaScript.h>
#include <JavaScriptCore/JSObjectInlines.h>
#include <wtf/text/WTFString.h>
#include <JavaScriptCore/JSCInlines.h>
#include "JavaScriptCore/ObjectConstructor.h"
#include "JavaScriptCore/SubspaceInlines.h"
#include "JavaScriptCore/RegExpObject.h"
#include "JavaScriptCore/JSPromise.h"
#include <JavaScriptCore/ObjectConstructor.h>
#include <JavaScriptCore/SubspaceInlines.h>
#include <JavaScriptCore/RegExpObject.h>
#include <JavaScriptCore/JSPromise.h>
#include "BunClientData.h"
#include "JavaScriptCore/RegularExpression.h"
#include <JavaScriptCore/RegularExpression.h>
namespace Zig {
@@ -34,7 +34,7 @@ static bool isValidNamespaceString(String& namespaceString)
return namespaceRegex->match(namespaceString) > -1;
}
static EncodedJSValue jsFunctionAppendOnLoadPluginBody(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe, BunPluginTarget target, BunPlugin::Base& plugin, void* ctx, OnAppendPluginCallback callback)
static JSC::EncodedJSValue jsFunctionAppendOnLoadPluginBody(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe, BunPluginTarget target, BunPlugin::Base& plugin, void* ctx, OnAppendPluginCallback callback)
{
JSC::VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
@@ -86,7 +86,7 @@ static EncodedJSValue jsFunctionAppendOnLoadPluginBody(JSC::JSGlobalObject* glob
return JSValue::encode(jsUndefined());
}
static EncodedJSValue jsFunctionAppendOnResolvePluginBody(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe, BunPluginTarget target, BunPlugin::Base& plugin, void* ctx, OnAppendPluginCallback callback)
static JSC::EncodedJSValue jsFunctionAppendOnResolvePluginBody(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe, BunPluginTarget target, BunPlugin::Base& plugin, void* ctx, OnAppendPluginCallback callback)
{
JSC::VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
@@ -139,7 +139,7 @@ static EncodedJSValue jsFunctionAppendOnResolvePluginBody(JSC::JSGlobalObject* g
return JSValue::encode(jsUndefined());
}
static EncodedJSValue jsFunctionAppendOnResolvePluginGlobal(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe, BunPluginTarget target)
static JSC::EncodedJSValue jsFunctionAppendOnResolvePluginGlobal(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe, BunPluginTarget target)
{
Zig::GlobalObject* global = Zig::jsCast<Zig::GlobalObject*>(globalObject);
@@ -148,7 +148,7 @@ static EncodedJSValue jsFunctionAppendOnResolvePluginGlobal(JSC::JSGlobalObject*
return jsFunctionAppendOnResolvePluginBody(globalObject, callframe, target, plugins, global->bunVM(), callback);
}
static EncodedJSValue jsFunctionAppendOnLoadPluginGlobal(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe, BunPluginTarget target)
static JSC::EncodedJSValue jsFunctionAppendOnLoadPluginGlobal(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe, BunPluginTarget target)
{
Zig::GlobalObject* global = Zig::jsCast<Zig::GlobalObject*>(globalObject);
@@ -187,7 +187,7 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionAppendOnResolvePluginBrowser, (JSC::JSGlobalO
return jsFunctionAppendOnResolvePluginGlobal(globalObject, callframe, BunPluginTargetBrowser);
}
extern "C" EncodedJSValue jsFunctionBunPluginClear(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe)
extern "C" JSC::EncodedJSValue jsFunctionBunPluginClear(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe)
{
Zig::GlobalObject* global = reinterpret_cast<Zig::GlobalObject*>(globalObject);
for (uint8_t i = 0; i < BunPluginTargetMax + 1; i++) {
@@ -200,7 +200,7 @@ extern "C" EncodedJSValue jsFunctionBunPluginClear(JSC::JSGlobalObject* globalOb
return JSValue::encode(jsUndefined());
}
extern "C" EncodedJSValue setupBunPlugin(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe, BunPluginTarget target)
extern "C" JSC::EncodedJSValue setupBunPlugin(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe, BunPluginTarget target)
{
JSC::VM& vm = globalObject->vm();
auto clientData = WebCore::clientData(vm);
@@ -326,7 +326,7 @@ extern "C" EncodedJSValue setupBunPlugin(JSC::JSGlobalObject* globalObject, JSC:
RELEASE_AND_RETURN(throwScope, JSValue::encode(jsUndefined()));
}
extern "C" EncodedJSValue jsFunctionBunPlugin(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe)
extern "C" JSC::EncodedJSValue jsFunctionBunPlugin(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe)
{
Zig::GlobalObject* global = reinterpret_cast<Zig::GlobalObject*>(globalObject);
BunPluginTarget target = global->defaultBunPluginTarget;

View File

@@ -2,8 +2,8 @@
#include "root.h"
#include "headers-handwritten.h"
#include "JavaScriptCore/JSGlobalObject.h"
#include "JavaScriptCore/Strong.h"
#include <JavaScriptCore/JSGlobalObject.h>
#include <JavaScriptCore/Strong.h>
#include "helpers.h"
extern "C" JSC_DECLARE_HOST_FUNCTION(jsFunctionBunPlugin);
@@ -67,7 +67,7 @@ public:
{
}
EncodedJSValue run(JSC::JSGlobalObject* globalObject, BunString* namespaceString, BunString* path);
JSC::EncodedJSValue run(JSC::JSGlobalObject* globalObject, BunString* namespaceString, BunString* path);
};
class OnResolve final : public Base {
@@ -78,7 +78,7 @@ public:
{
}
EncodedJSValue run(JSC::JSGlobalObject* globalObject, BunString* namespaceString, BunString* path, BunString* importer);
JSC::EncodedJSValue run(JSC::JSGlobalObject* globalObject, BunString* namespaceString, BunString* path, BunString* importer);
};
};

View File

@@ -1,10 +1,9 @@
#include "Process.h"
#include "JavaScriptCore/InternalFieldTuple.h"
#include "JavaScriptCore/JSMicrotask.h"
#include "JavaScriptCore/ObjectConstructor.h"
#include "JavaScriptCore/NumberPrototype.h"
#include "BunProcess.h"
#include <JavaScriptCore/InternalFieldTuple.h>
#include <JavaScriptCore/JSMicrotask.h>
#include <JavaScriptCore/ObjectConstructor.h>
#include <JavaScriptCore/NumberPrototype.h>
#include "node_api.h"
#include <dlfcn.h>
#include "ZigGlobalObject.h"
#include "headers.h"
#include "JSEnvironmentVariableMap.h"
@@ -16,9 +15,17 @@
#include <JavaScriptCore/LazyProperty.h>
#include <JavaScriptCore/LazyPropertyInlines.h>
#include <JavaScriptCore/VMTrapsInlines.h>
#include <termios.h>
#ifndef WIN32
#include <errno.h>
#include <dlfcn.h>
#include <sys/ioctl.h>
#include <termios.h>
#else
#include <uv.h>
#include <io.h>
#include <fcntl.h>
#endif
#include "JSNextTickQueue.h"
#pragma mark - Node.js Process
@@ -119,6 +126,32 @@ JSC_DEFINE_CUSTOM_SETTER(Process_defaultSetter,
static bool getWindowSize(int fd, size_t* width, size_t* height)
{
#if OS(WINDOWS)
CONSOLE_SCREEN_BUFFER_INFO csbi;
HANDLE handle = INVALID_HANDLE_VALUE;
switch (fd) {
case 0:
handle = GetStdHandle(STD_INPUT_HANDLE);
break;
case 1:
handle = GetStdHandle(STD_OUTPUT_HANDLE);
break;
case 2:
handle = GetStdHandle(STD_ERROR_HANDLE);
break;
default:
break;
}
if (handle == INVALID_HANDLE_VALUE)
return false;
if (!GetConsoleScreenBufferInfo(handle, &csbi))
return false;
*width = csbi.srWindow.Right - csbi.srWindow.Left + 1;
*height = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
return true;
#else
struct winsize ws;
int err;
do
@@ -132,6 +165,7 @@ static bool getWindowSize(int fd, size_t* width, size_t* height)
*height = ws.ws_row;
return true;
#endif
}
JSC_DEFINE_HOST_FUNCTION(Process_functionInternalGetWindowSize,
@@ -201,13 +235,20 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionDlopen,
WTF::String filename = callFrame->uncheckedArgument(1).toWTFString(globalObject);
RETURN_IF_EXCEPTION(scope, {});
#if OS(WINDOWS)
CString utf8 = filename.utf8();
HMODULE handle = LoadLibraryA(utf8.data());
#else
CString utf8 = filename.utf8();
void* handle = dlopen(utf8.data(), RTLD_LAZY);
#endif
if (!handle) {
#if OS(WINDOWS)
WTF::String msg = makeString("LoadLibraryA failed with error code: "_s, GetLastError());
#else
WTF::String msg = WTF::String::fromUTF8(dlerror());
#endif
JSC::throwTypeError(globalObject, scope, msg);
return JSC::JSValue::encode(JSC::JSValue {});
}
@@ -228,13 +269,24 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionDlopen,
JSC::EncodedJSValue (*napi_register_module_v1)(JSC::JSGlobalObject * globalObject,
JSC::EncodedJSValue exports);
#if OS(WINDOWS)
#define dlsym GetProcAddress
#endif
napi_register_module_v1 = reinterpret_cast<JSC::EncodedJSValue (*)(JSC::JSGlobalObject*,
JSC::EncodedJSValue)>(
dlsym(handle, "napi_register_module_v1"));
#if OS(WINDOWS)
#undef dlsym
#endif
if (!napi_register_module_v1) {
#if OS(WINDOWS)
FreeLibrary(handle);
#else
dlclose(handle);
#endif
JSC::throwTypeError(globalObject, scope, "symbol 'napi_register_module_v1' not found in native module. Is this a Node API (napi) module?"_s);
return JSC::JSValue::encode(JSC::JSValue {});
}
@@ -245,6 +297,8 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionDlopen,
JSC_DEFINE_HOST_FUNCTION(Process_functionUmask,
(JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
#if !OS(WINDOWS)
if (callFrame->argumentCount() == 0 || callFrame->argument(0).isUndefined()) {
mode_t currentMask = umask(0);
umask(currentMask);
@@ -277,6 +331,9 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionUmask,
}
return JSC::JSValue::encode(JSC::jsNumber(umask(newUmask)));
#else
return JSC::JSValue::encode(JSC::jsNumber(0));
#endif
}
extern "C" uint64_t Bun__readOriginTimer(void*);
@@ -437,7 +494,7 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionChdir,
return JSC::JSValue::encode(result);
}
#if !OS(WINDOWS)
static HashMap<String, int>* signalNameToNumberMap = nullptr;
static HashMap<int, String>* signalNumberToNameMap = nullptr;
@@ -655,14 +712,20 @@ static void onDidChangeListeners(EventEmitter& eventEmitter, const Identifier& e
}
}
}
#endif
void Process::emitSignalEvent(int signalNumber)
{
#if !OS(WINDOWS)
String signalName = signalNumberToNameMap->get(signalNumber);
Identifier signalNameIdentifier = Identifier::fromString(vm(), signalName);
MarkedArgumentBuffer args;
args.append(jsNumber(signalNumber));
wrapped().emitForBindings(signalNameIdentifier, args);
#else
UNUSED_PARAM(signalNumber);
#endif
}
Process::~Process()
@@ -809,7 +872,11 @@ static JSValue constructVersions(VM& vm, JSObject* processObject)
JSC::JSValue(JSC::jsString(vm, makeString(Bun__versions_usockets))), 0);
object->putDirect(vm, JSC::Identifier::fromString(vm, "v8"_s), JSValue(JSC::jsString(vm, makeString("10.8.168.20-node.8"_s))), 0);
#if OS(WINDOWS)
object->putDirect(vm, JSC::Identifier::fromString(vm, "uv"_s), JSValue(JSC::jsString(vm, makeString(uv_version_string()))), 0);
#else
object->putDirect(vm, JSC::Identifier::fromString(vm, "uv"_s), JSValue(JSC::jsString(vm, makeString("1.44.2"_s))), 0);
#endif
object->putDirect(vm, JSC::Identifier::fromString(vm, "napi"_s), JSValue(JSC::jsString(vm, makeString("8"_s))), 0);
object->putDirect(vm, JSC::Identifier::fromString(vm, "modules"_s),
@@ -920,6 +987,10 @@ static JSValue constructStderr(VM& vm, JSObject* processObject)
return constructStdioWriteStream(globalObject, 2);
}
#if OS(WINDOWS)
#define STDIN_FILENO 0
#endif
static JSValue constructStdin(VM& vm, JSObject* processObject)
{
auto* globalObject = Bun__getDefaultGlobal();
@@ -971,7 +1042,11 @@ static JSValue constructPid(VM& vm, JSObject* processObject)
static JSValue constructPpid(VM& vm, JSObject* processObject)
{
#if OS(WINDOWS)
return jsUndefined();
#else
return jsNumber(getppid());
#endif
}
static JSValue constructArgv0(VM& vm, JSObject* processObject)
@@ -1000,13 +1075,9 @@ static JSValue constructArgv(VM& vm, JSObject* processObject)
static JSValue constructArch(VM& vm, JSObject* processObject)
{
#if defined(__x86_64__)
#if CPU(X86_64)
return JSC::jsString(vm, makeAtomString("x64"));
#elif defined(__i386__)
return JSC::jsString(vm, makeAtomString("x86"));
#elif defined(__arm__)
return JSC::jsString(vm, makeAtomString("arm"));
#elif defined(__aarch64__)
#elif CPU(ARM64)
return JSC::jsString(vm, makeAtomString("arm64"));
#else
#error "Unknown architecture"
@@ -1019,6 +1090,8 @@ static JSValue constructPlatform(VM& vm, JSObject* processObject)
return JSC::jsString(vm, makeAtomString("darwin"));
#elif defined(__linux__)
return JSC::jsString(vm, makeAtomString("linux"));
#elif OS(WINDOWS)
return JSC::jsString(vm, makeAtomString("win32"));
#else
#error "Unknown platform"
#endif
@@ -1050,6 +1123,28 @@ static JSValue constructEnv(VM& vm, JSObject* processObject)
return globalObject->processEnvObject();
}
#if OS(WINDOWS)
static int getuid()
{
return 0;
}
static int geteuid()
{
return 0;
}
static int getegid()
{
return 0;
}
static int getgid()
{
return 0;
}
#endif
JSC_DEFINE_HOST_FUNCTION(Process_functiongetuid, (JSGlobalObject * globalObject, CallFrame* callFrame))
{
return JSValue::encode(jsNumber(getuid()));
@@ -1072,6 +1167,7 @@ JSC_DEFINE_HOST_FUNCTION(Process_functiongetgid, (JSGlobalObject * globalObject,
JSC_DEFINE_HOST_FUNCTION(Process_functiongetgroups, (JSGlobalObject * globalObject, CallFrame* callFrame))
{
#if !OS(WINDOWS)
auto& vm = globalObject->vm();
int ngroups = getgroups(0, nullptr);
auto throwScope = DECLARE_THROW_SCOPE(vm);
@@ -1098,6 +1194,9 @@ JSC_DEFINE_HOST_FUNCTION(Process_functiongetgroups, (JSGlobalObject * globalObje
groups->push(globalObject, jsNumber(egid));
return JSValue::encode(groups);
#else
return JSValue::encode(jsUndefined());
#endif
}
JSC_DEFINE_HOST_FUNCTION(Process_functionAssert, (JSGlobalObject * globalObject, CallFrame* callFrame))
@@ -1244,11 +1343,19 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionCpuUsage,
{
JSC::VM& vm = globalObject->vm();
auto throwScope = DECLARE_THROW_SCOPE(vm);
#if !OS(WINDOWS)
struct rusage rusage;
if (getrusage(RUSAGE_SELF, &rusage) != 0) {
throwSystemError(throwScope, globalObject, "Failed to get CPU usage"_s, "getrusage"_s, errno);
return JSValue::encode(jsUndefined());
}
#else
uv_rusage_t rusage;
if (uv_getrusage(&rusage) != 0) {
throwSystemError(throwScope, globalObject, "Failed to get CPU usage"_s, "uv_getrusage"_s, errno);
return JSValue::encode(jsUndefined());
}
#endif
auto* process = getProcessObject(globalObject, callFrame->thisValue());
@@ -1387,8 +1494,10 @@ int getRSS(size_t* rss)
err:
return EINVAL;
#elif OS(WINDOWS)
return uv_resident_set_memory(rss);
#else
#error "Unsupported platform"
#error "Unknown platform"
#endif
}
@@ -1460,15 +1569,15 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionOpenStdin, (JSGlobalObject * globalObje
}
auto throwScope = DECLARE_THROW_SCOPE(vm);
if (JSValue stdin = global->processObject()->getIfPropertyExists(globalObject, Identifier::fromString(vm, "stdin"_s))) {
if (JSValue stdinValue = global->processObject()->getIfPropertyExists(globalObject, Identifier::fromString(vm, "stdin"_s))) {
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
if (!stdin.isObject()) {
if (!stdinValue.isObject()) {
throwTypeError(globalObject, throwScope, "stdin is not an object"_s);
return JSValue::encode(jsUndefined());
}
JSValue resumeValue = stdin.getObject()->getIfPropertyExists(globalObject, Identifier::fromString(vm, "resume"_s));
JSValue resumeValue = stdinValue.getObject()->getIfPropertyExists(globalObject, Identifier::fromString(vm, "resume"_s));
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
if (!resumeValue.isUndefinedOrNull()) {
auto resumeFunction = jsDynamicCast<JSFunction*>(resumeValue);
@@ -1480,11 +1589,11 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionOpenStdin, (JSGlobalObject * globalObje
auto callData = getCallData(resumeFunction);
MarkedArgumentBuffer args;
JSC::call(globalObject, resumeFunction, callData, stdin, args);
JSC::call(globalObject, resumeFunction, callData, stdinValue, args);
RETURN_IF_EXCEPTION(throwScope, JSValue::encode(jsUndefined()));
}
RELEASE_AND_RETURN(throwScope, JSValue::encode(stdin));
RELEASE_AND_RETURN(throwScope, JSValue::encode(stdinValue));
}
RELEASE_AND_RETURN(throwScope, JSValue::encode(jsUndefined()));
@@ -1639,9 +1748,19 @@ JSC_DEFINE_CUSTOM_SETTER(setProcessDebugPort,
JSC_DEFINE_CUSTOM_GETTER(processTitle, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName))
{
#if !OS(WINDOWS)
ZigString str;
Bun__Process__getTitle(globalObject, &str);
return JSValue::encode(Zig::toJSStringValue(str, globalObject));
#else
auto& vm = globalObject->vm();
char title[1024];
if (uv_get_process_title(title, sizeof(title)) != 0) {
return JSValue::encode(jsString(vm, String("bun"_s)));
}
return JSValue::encode(jsString(vm, WTF::String::fromUTF8(title)));
#endif
}
JSC_DEFINE_CUSTOM_SETTER(setProcessTitle,
@@ -1649,17 +1768,22 @@ JSC_DEFINE_CUSTOM_SETTER(setProcessTitle,
JSC::EncodedJSValue value, JSC::PropertyName))
{
JSC::VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
JSC::JSObject* thisObject = JSC::jsDynamicCast<JSC::JSObject*>(JSValue::decode(thisValue));
JSC::JSString* jsString = JSC::jsDynamicCast<JSC::JSString*>(JSValue::decode(value));
if (!thisObject || !jsString) {
return false;
}
#if !OS(WINDOWS)
ZigString str = Zig::toZigString(jsString, globalObject);
Bun__Process__setTitle(globalObject, &str);
return true;
#else
WTF::String str = jsString->value(globalObject);
RETURN_IF_EXCEPTION(scope, false);
CString cstr = str.utf8();
return uv_set_process_title(cstr.data()) == 0;
#endif
}
JSC_DEFINE_HOST_FUNCTION(Process_functionCwd,
@@ -1687,7 +1811,12 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionReallyKill,
int signal = callFrame->argument(1).toInt32(globalObject);
RETURN_IF_EXCEPTION(scope, {});
#if !OS(WINDOWS)
int result = kill(pid, signal);
#else
int result = uv_kill(pid, signal);
#endif
if (result < 0) {
throwSystemError(scope, globalObject, "kill"_s, errno);
}
@@ -1707,7 +1836,7 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionKill,
}
JSC::JSValue signalValue = callFrame->argument(1);
#if !OS(WINDOWS)
int signal = SIGTERM;
if (signalValue.isNumber()) {
@@ -1730,6 +1859,21 @@ JSC_DEFINE_HOST_FUNCTION(Process_functionKill,
}
int result = kill(pid, signal);
#else
int signal = 1;
if (signalValue.isNumber()) {
signal = signalValue.toInt32(globalObject);
RETURN_IF_EXCEPTION(scope, {});
} else if (signalValue.isString()) {
throwTypeError(globalObject, scope, "TODO: implement this function with strings on Windows! Sorry!!"_s);
RETURN_IF_EXCEPTION(scope, {});
} else if (!signalValue.isUndefinedOrNull()) {
throwTypeError(globalObject, scope, "signal must be a string or number"_s);
return JSValue::encode(jsUndefined());
}
int result = uv_kill(pid, signal);
#endif
if (result < 0) {
throwSystemError(scope, globalObject, "kill"_s, errno);
@@ -1832,7 +1976,7 @@ extern "C" void Process__emitDisconnectEvent(Zig::GlobalObject* global)
@end
*/
#include "Process.lut.h"
#include "BunProcess.lut.h"
const JSC::ClassInfo Process::s_info = { "Process"_s, &Base::s_info, &processObjectTable, nullptr,
CREATE_METHOD_TABLE(Process) };
@@ -1840,7 +1984,9 @@ void Process::finishCreation(JSC::VM& vm)
{
Base::finishCreation(vm);
#ifndef WIN32
this->wrapped().onDidChangeListener = &onDidChangeListeners;
#endif
this->cpuUsageStructure.initLater([](const JSC::LazyProperty<JSC::JSObject, JSC::Structure>::Initializer& init) {
init.set(constructCPUUsageStructure(init.vm, init.owner->globalObject()));

View File

@@ -1,9 +1,9 @@
#include "root.h"
#include "headers-handwritten.h"
#include "JavaScriptCore/JSCJSValueInlines.h"
#include <JavaScriptCore/JSCJSValueInlines.h>
#include "helpers.h"
#include "simdutf.h"
#include "wtf/text/ExternalStringImpl.h"
#include <wtf/text/ExternalStringImpl.h>
#include "GCDefferalContext.h"
#include <JavaScriptCore/JSONObject.h>
#include <wtf/text/AtomString.h>
@@ -278,7 +278,7 @@ extern "C" BunString BunString__createExternal(const char* bytes, size_t length,
return { BunStringTag::WTFStringImpl, { .wtf = &impl.leakRef() } };
}
extern "C" EncodedJSValue BunString__toJSON(
extern "C" JSC::EncodedJSValue BunString__toJSON(
JSC::JSGlobalObject* globalObject,
BunString* bunString)
{
@@ -291,7 +291,7 @@ extern "C" EncodedJSValue BunString__toJSON(
return JSC::JSValue::encode(result);
}
extern "C" EncodedJSValue BunString__createArray(
extern "C" JSC::EncodedJSValue BunString__createArray(
JSC::JSGlobalObject* globalObject,
const BunString* ptr, size_t length)
{

View File

@@ -36,26 +36,24 @@
#include "root.h"
#include "headers-handwritten.h"
#include "ZigGlobalObject.h"
#include "JavaScriptCore/JSSourceCode.h"
#include "JavaScriptCore/JSString.h"
#include "JavaScriptCore/JSValueInternal.h"
#include "JavaScriptCore/JSVirtualMachineInternal.h"
#include "JavaScriptCore/ObjectConstructor.h"
#include "JavaScriptCore/OptionsList.h"
#include "JavaScriptCore/ParserError.h"
#include "JavaScriptCore/ScriptExecutable.h"
#include "JavaScriptCore/SourceOrigin.h"
#include "JavaScriptCore/StackFrame.h"
#include "JavaScriptCore/StackVisitor.h"
#include <JavaScriptCore/JSSourceCode.h>
#include <JavaScriptCore/JSString.h>
#include <JavaScriptCore/ObjectConstructor.h>
#include <JavaScriptCore/OptionsList.h>
#include <JavaScriptCore/ParserError.h>
#include <JavaScriptCore/ScriptExecutable.h>
#include <JavaScriptCore/SourceOrigin.h>
#include <JavaScriptCore/StackFrame.h>
#include <JavaScriptCore/StackVisitor.h>
#include "BunClientData.h"
#include "JavaScriptCore/Identifier.h"
#include <JavaScriptCore/Identifier.h>
#include "ImportMetaObject.h"
#include "JavaScriptCore/TypedArrayInlines.h"
#include "JavaScriptCore/PropertyNameArray.h"
#include "JavaScriptCore/JSWeakMap.h"
#include "JavaScriptCore/JSWeakMapInlines.h"
#include "JavaScriptCore/JSWithScope.h"
#include <JavaScriptCore/TypedArrayInlines.h>
#include <JavaScriptCore/PropertyNameArray.h>
#include <JavaScriptCore/JSWeakMap.h>
#include <JavaScriptCore/JSWeakMapInlines.h>
#include <JavaScriptCore/JSWithScope.h>
#include <JavaScriptCore/DFGAbstractHeap.h>
#include <JavaScriptCore/Completion.h>
@@ -65,7 +63,7 @@
#include <JavaScriptCore/JSMapInlines.h>
#include <JavaScriptCore/GetterSetter.h>
#include "ZigSourceProvider.h"
#include "JavaScriptCore/FunctionPrototype.h"
#include <JavaScriptCore/FunctionPrototype.h>
#include "CommonJSModuleRecord.h"
#include <JavaScriptCore/JSModuleNamespaceObject.h>
#include <JavaScriptCore/JSSourceCode.h>
@@ -228,7 +226,7 @@ void RequireFunctionPrototype::finishCreation(JSC::VM& vm)
this->putDirect(
vm,
JSC::Identifier::fromString(vm, "main"_s),
JSC::GetterSetter::create(vm, globalObject(), requireDotMainFunction, JSValue()),
JSC::GetterSetter::create(vm, globalObject(), requireDotMainFunction, jsUndefined()),
PropertyAttribute::Builtin | PropertyAttribute::Accessor | PropertyAttribute::ReadOnly | 0);
auto extensions = constructEmptyObject(globalObject());
@@ -277,7 +275,7 @@ JSC_DEFINE_CUSTOM_SETTER(setterPath,
return true;
}
extern "C" EncodedJSValue Resolver__propForRequireMainPaths(JSGlobalObject*);
extern "C" JSC::EncodedJSValue Resolver__propForRequireMainPaths(JSGlobalObject*);
JSC_DEFINE_CUSTOM_GETTER(getterPaths, (JSC::JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::PropertyName))
{

View File

@@ -25,7 +25,7 @@ public:
mutable JSC::WriteBarrier<JSC::JSString> m_id;
mutable JSC::WriteBarrier<JSC::Unknown> m_filename;
mutable JSC::WriteBarrier<JSC::JSString> m_dirname;
mutable JSC::WriteBarrier<Unknown> m_paths;
mutable JSC::WriteBarrier<JSC::Unknown> m_paths;
mutable JSC::WriteBarrier<JSC::JSSourceCode> sourceCode;
bool ignoreESModuleAnnotation { false };

View File

@@ -30,7 +30,7 @@
#include "root.h"
#include "ExceptionCode.h"
#include "wtf/text/WTFString.h"
#include <wtf/text/WTFString.h>
namespace WebCore {

View File

@@ -30,7 +30,7 @@
#include "config.h"
#include "DOMFormData.h"
#include "wtf/URLParser.h"
#include <wtf/URLParser.h>
namespace WebCore {

View File

@@ -32,7 +32,7 @@
// #include "PublicURLManager.h"
// #include "ResourceRequest.h"
#include "URLSearchParams.h"
// #include "wtf/MainThread.h"
// #include <wtf/MainThread.h>
namespace WebCore {

View File

@@ -30,8 +30,8 @@
#include "ExceptionOr.h"
#include "URLDecomposition.h"
#include "wtf/URL.h"
#include "wtf/WeakPtr.h"
#include <wtf/URL.h>
#include <wtf/WeakPtr.h>
namespace WebCore {

View File

@@ -2,7 +2,7 @@
#include "root.h"
#include "wtf/Forward.h"
#include <wtf/Forward.h>
namespace WebCore {

View File

@@ -26,7 +26,7 @@
#include "WebCoreJSClientData.h"
// #include "WindowProxy.h"
#include "ZigGlobalObject.h"
#include "wtf/MainThread.h"
#include <wtf/MainThread.h>
namespace WebCore {

View File

@@ -29,7 +29,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "root.h"
#include "ExceptionCode.h"
#include "wtf/text/WTFString.h"
#include <wtf/text/WTFString.h>
namespace WebCore {

View File

@@ -20,7 +20,7 @@
#include "root.h"
#include "wtf/EnumTraits.h"
#include <wtf/EnumTraits.h>
namespace WebCore {

View File

@@ -29,9 +29,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "root.h"
#include "Exception.h"
#include "wtf/CrossThreadCopier.h"
#include "wtf/Expected.h"
#include "wtf/StdLibExtras.h"
#include <wtf/CrossThreadCopier.h>
#include <wtf/Expected.h>
#include <wtf/StdLibExtras.h>
namespace WebCore {

View File

@@ -21,23 +21,23 @@
#include "JSDOMWrapperCache.h"
#include "ScriptExecutionContext.h"
#include "WebCoreJSClientData.h"
#include "JavaScriptCore/FunctionPrototype.h"
#include "JavaScriptCore/HeapAnalyzer.h"
#include <JavaScriptCore/FunctionPrototype.h>
#include <JavaScriptCore/HeapAnalyzer.h>
#include "JavaScriptCore/JSDestructibleObjectHeapCellType.h"
#include "JavaScriptCore/SlotVisitorMacros.h"
#include "JavaScriptCore/SubspaceInlines.h"
#include "wtf/GetPtr.h"
#include "wtf/PointerPreparations.h"
#include "wtf/URL.h"
#include "JavaScriptCore/BuiltinNames.h"
#include <JavaScriptCore/JSDestructibleObjectHeapCellType.h>
#include <JavaScriptCore/SlotVisitorMacros.h>
#include <JavaScriptCore/SubspaceInlines.h>
#include <wtf/GetPtr.h>
#include <wtf/PointerPreparations.h>
#include <wtf/URL.h>
#include <JavaScriptCore/BuiltinNames.h>
#include "JSBufferEncodingType.h"
#include "JavaScriptCore/JSBase.h"
#include <JavaScriptCore/JSBase.h>
#include "JSDOMURL.h"
#include "JavaScriptCore/JSNativeStdFunction.h"
#include "JavaScriptCore/GetterSetter.h"
#include <JavaScriptCore/JSNativeStdFunction.h>
#include <JavaScriptCore/GetterSetter.h>
#include <JavaScriptCore/LazyProperty.h>
#include <JavaScriptCore/LazyPropertyInlines.h>
#include <JavaScriptCore/VMTrapsInlines.h>
@@ -47,7 +47,7 @@ namespace Zig {
using namespace JSC;
using namespace WebCore;
static EncodedJSValue functionRequireResolve(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame, const WTF::String& fromStr)
static JSC::EncodedJSValue functionRequireResolve(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame, const WTF::String& fromStr)
{
JSC::VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
@@ -142,7 +142,7 @@ JSC_DEFINE_HOST_FUNCTION(jsFunctionRequireResolve, (JSC::JSGlobalObject * global
return functionRequireResolve(globalObject, callFrame, fromStr);
}
extern "C" EncodedJSValue functionImportMeta__resolveSync(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame)
extern "C" JSC::EncodedJSValue functionImportMeta__resolveSync(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame)
{
JSC::VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
@@ -222,7 +222,7 @@ extern "C" EncodedJSValue functionImportMeta__resolveSync(JSC::JSGlobalObject* g
return result;
}
extern "C" EncodedJSValue functionImportMeta__resolveSyncPrivate(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame)
extern "C" JSC::EncodedJSValue functionImportMeta__resolveSyncPrivate(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame)
{
JSC::VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
@@ -333,7 +333,7 @@ Zig::ImportMetaObject* ImportMetaObject::create(JSC::JSGlobalObject* jslobalObje
return Zig::ImportMetaObject::create(vm, globalObject, structure, view);
}
JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_url, (JSGlobalObject * globalObject, EncodedJSValue thisValue, PropertyName propertyName))
JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_url, (JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, PropertyName propertyName))
{
ImportMetaObject* thisObject = jsDynamicCast<ImportMetaObject*>(JSValue::decode(thisValue));
if (UNLIKELY(!thisObject))
@@ -341,7 +341,7 @@ JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_url, (JSGlobalObject * globalO
return JSValue::encode(thisObject->urlProperty.getInitializedOnMainThread(thisObject));
}
JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_dir, (JSGlobalObject * globalObject, EncodedJSValue thisValue, PropertyName propertyName))
JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_dir, (JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, PropertyName propertyName))
{
ImportMetaObject* thisObject = jsDynamicCast<ImportMetaObject*>(JSValue::decode(thisValue));
if (UNLIKELY(!thisObject))
@@ -349,7 +349,7 @@ JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_dir, (JSGlobalObject * globalO
return JSValue::encode(thisObject->dirProperty.getInitializedOnMainThread(thisObject));
}
JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_file, (JSGlobalObject * globalObject, EncodedJSValue thisValue, PropertyName propertyName))
JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_file, (JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, PropertyName propertyName))
{
ImportMetaObject* thisObject = jsDynamicCast<ImportMetaObject*>(JSValue::decode(thisValue));
if (UNLIKELY(!thisObject))
@@ -357,7 +357,7 @@ JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_file, (JSGlobalObject * global
return JSValue::encode(thisObject->fileProperty.getInitializedOnMainThread(thisObject));
}
JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_path, (JSGlobalObject * globalObject, EncodedJSValue thisValue, PropertyName propertyName))
JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_path, (JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, PropertyName propertyName))
{
ImportMetaObject* thisObject = jsDynamicCast<ImportMetaObject*>(JSValue::decode(thisValue));
if (UNLIKELY(!thisObject))
@@ -365,7 +365,7 @@ JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_path, (JSGlobalObject * global
return JSValue::encode(thisObject->pathProperty.getInitializedOnMainThread(thisObject));
}
JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_require, (JSGlobalObject * globalObject, EncodedJSValue thisValue, PropertyName propertyName))
JSC_DEFINE_CUSTOM_GETTER(jsImportMetaObjectGetter_require, (JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, PropertyName propertyName))
{
ImportMetaObject* thisObject = jsDynamicCast<ImportMetaObject*>(JSValue::decode(thisValue));
if (UNLIKELY(!thisObject))
@@ -420,7 +420,7 @@ public:
this->putDirect(
vm,
builtinNames.mainPublicName(),
GetterSetter::create(vm, globalObject, JSFunction::create(vm, importMetaObjectMainCodeGenerator(vm), globalObject), nullptr),
GetterSetter::create(vm, globalObject, JSFunction::create(vm, importMetaObjectMainCodeGenerator(vm), globalObject), jsUndefined()),
JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::Accessor | JSC::PropertyAttribute::Builtin | 0);
}

View File

@@ -1,12 +1,12 @@
#include "InternalModuleRegistry.h"
#include "ZigGlobalObject.h"
#include "JavaScriptCore/BuiltinUtils.h"
#include "JavaScriptCore/JSFunction.h"
#include "JavaScriptCore/LazyProperty.h"
#include "JavaScriptCore/LazyPropertyInlines.h"
#include "JavaScriptCore/VMTrapsInlines.h"
#include "JavaScriptCore/JSModuleLoader.h"
#include <JavaScriptCore/BuiltinUtils.h>
#include <JavaScriptCore/JSFunction.h>
#include <JavaScriptCore/LazyProperty.h>
#include <JavaScriptCore/LazyPropertyInlines.h>
#include <JavaScriptCore/VMTrapsInlines.h>
#include <JavaScriptCore/JSModuleLoader.h>
#include "InternalModuleRegistryConstants.h"
@@ -61,7 +61,8 @@ static void maybeAddCodeCoverage(JSC::VM& vm, const JSC::SourceCode& code)
ASSERT_INTERNAL_MODULE(result, moduleName); \
return result;
#if BUN_DEBUG
#if BUN_DEBUG && __has_include("../../src/js/out/DebugPath.h")
#include "../../src/js/out/DebugPath.h"
#define ASSERT_INTERNAL_MODULE(result, moduleName) \
if (!result || !result.isCell() || !jsDynamicCast<JSObject*>(result)) { \

View File

@@ -1,7 +1,7 @@
#pragma once
#include "root.h"
#include "JavaScriptCore/JSInternalFieldObjectImpl.h"
#include "JavaScriptCore/JSInternalFieldObjectImplInlines.h"
#include <JavaScriptCore/JSInternalFieldObjectImpl.h>
#include <JavaScriptCore/JSInternalFieldObjectImplInlines.h>
#include "BunClientData.h"
#include "../../../src/js/out/InternalModuleRegistry+numberOfModules.h"
@@ -29,8 +29,8 @@ public:
enum Field : uint8_t {
#include "../../../src/js/out/InternalModuleRegistry+enum.h"
};
const WriteBarrier<Unknown>& internalField(Field field) const { return Base::internalField(static_cast<uint32_t>(field)); }
WriteBarrier<Unknown>& internalField(Field field) { return Base::internalField(static_cast<uint32_t>(field)); }
const JSC::WriteBarrier<JSC::Unknown>& internalField(Field field) const { return Base::internalField(static_cast<uint32_t>(field)); }
JSC::WriteBarrier<JSC::Unknown>& internalField(Field field) { return Base::internalField(static_cast<uint32_t>(field)); }
template<typename, SubspaceAccess mode>
static GCClient::IsoSubspace* subspaceFor(JSC::VM& vm)

View File

@@ -19,8 +19,8 @@
#include "JSDOMWrapperCache.h"
#include "ScriptExecutionContext.h"
#include "WebCoreJSClientData.h"
#include "JavaScriptCore/FunctionPrototype.h"
#include "JavaScriptCore/HeapAnalyzer.h"
#include <JavaScriptCore/FunctionPrototype.h>
#include <JavaScriptCore/HeapAnalyzer.h>
#include <JavaScriptCore/JSFunction.h>
#include <JavaScriptCore/InternalFunction.h>
@@ -28,22 +28,26 @@
#include <JavaScriptCore/LazyClassStructureInlines.h>
#include <JavaScriptCore/FunctionPrototype.h>
#include "JavaScriptCore/JSDestructibleObjectHeapCellType.h"
#include "JavaScriptCore/SlotVisitorMacros.h"
#include "JavaScriptCore/SubspaceInlines.h"
#include "wtf/GetPtr.h"
#include "wtf/PointerPreparations.h"
#include "wtf/URL.h"
#include "wtf/text/WTFString.h"
#include "JavaScriptCore/BuiltinNames.h"
#include <JavaScriptCore/JSDestructibleObjectHeapCellType.h>
#include <JavaScriptCore/SlotVisitorMacros.h>
#include <JavaScriptCore/SubspaceInlines.h>
#include <wtf/GetPtr.h>
#include <wtf/PointerPreparations.h>
#include <wtf/URL.h>
#include <wtf/text/WTFString.h>
#include <JavaScriptCore/BuiltinNames.h>
#include "JSBufferEncodingType.h"
#include "JavaScriptCore/JSBase.h"
#include <JavaScriptCore/JSBase.h>
#if ENABLE(MEDIA_SOURCE)
#include "BufferMediaSource.h"
#include "JSMediaSource.h"
#endif
#ifdef WIN32
#include "musl-memmem.h"
#endif
#include <JavaScriptCore/DOMJITAbstractHeap.h>
#include "DOMJITIDLConvert.h"
#include "DOMJITIDLType.h"
@@ -51,8 +55,8 @@
#include "DOMJITHelpers.h"
#include <JavaScriptCore/DFGAbstractHeap.h>
// #include "JavaScriptCore/JSTypedArrayViewPrototype.h"
#include "JavaScriptCore/JSArrayBufferViewInlines.h"
// #include <JavaScriptCore/JSTypedArrayViewPrototype.h>
#include <JavaScriptCore/JSArrayBufferViewInlines.h>
using namespace JSC;
using namespace WebCore;
@@ -218,7 +222,7 @@ JSC::EncodedJSValue JSBuffer__bufferFromPointerAndLengthAndDeinit(JSC::JSGlobalO
namespace WebCore {
using namespace JSC;
static inline EncodedJSValue writeToBuffer(JSC::JSGlobalObject* lexicalGlobalObject, JSArrayBufferView* castedThis, JSString* str, uint32_t offset, uint32_t length, BufferEncodingType encoding)
static inline JSC::EncodedJSValue writeToBuffer(JSC::JSGlobalObject* lexicalGlobalObject, JSArrayBufferView* castedThis, JSString* str, uint32_t offset, uint32_t length, BufferEncodingType encoding)
{
if (UNLIKELY(str->length() == 0))
return JSC::JSValue::encode(JSC::jsNumber(0));
@@ -243,6 +247,9 @@ static inline EncodedJSValue writeToBuffer(JSC::JSGlobalObject* lexicalGlobalObj
}
break;
}
default: {
break;
}
}
return JSC::JSValue::encode(JSC::jsNumber(written));
@@ -271,7 +278,7 @@ static inline JSC::JSUint8Array* JSBuffer__bufferFromLengthAsArray(JSC::JSGlobal
RELEASE_AND_RETURN(throwScope, uint8Array);
}
extern "C" EncodedJSValue JSBuffer__bufferFromLength(JSC::JSGlobalObject* lexicalGlobalObject, int64_t length)
extern "C" JSC::EncodedJSValue JSBuffer__bufferFromLength(JSC::JSGlobalObject* lexicalGlobalObject, int64_t length)
{
return JSC::JSValue::encode(JSBuffer__bufferFromLengthAsArray(lexicalGlobalObject, length));
}
@@ -310,18 +317,18 @@ EncodedJSValue JSBuffer__bufferFromPointerAndLength(JSC::JSGlobalObject* lexical
}
// new Buffer()
static inline EncodedJSValue constructBufferEmpty(JSGlobalObject* lexicalGlobalObject)
static inline JSC::EncodedJSValue constructBufferEmpty(JSGlobalObject* lexicalGlobalObject)
{
return JSBuffer__bufferFromLength(lexicalGlobalObject, 0);
}
// new Buffer(size)
static inline EncodedJSValue constructBufferFromLength(JSGlobalObject* lexicalGlobalObject, CallFrame* callFrame)
static inline JSC::EncodedJSValue constructBufferFromLength(JSGlobalObject* lexicalGlobalObject, CallFrame* callFrame)
{
return jsBufferConstructorFunction_allocUnsafeBody(lexicalGlobalObject, callFrame);
}
static EncodedJSValue constructFromEncoding(JSGlobalObject* lexicalGlobalObject, JSString* str, WebCore::BufferEncodingType encoding)
static JSC::EncodedJSValue constructFromEncoding(JSGlobalObject* lexicalGlobalObject, JSString* str, WebCore::BufferEncodingType encoding)
{
auto& vm = JSC::getVM(lexicalGlobalObject);
auto scope = DECLARE_THROW_SCOPE(vm);
@@ -345,6 +352,9 @@ static EncodedJSValue constructFromEncoding(JSGlobalObject* lexicalGlobalObject,
result = JSBuffer__bufferFromPointerAndLength(lexicalGlobalObject, view.characters8(), view.length());
break;
}
default: {
break;
}
}
} else {
switch (encoding) {
@@ -363,6 +373,9 @@ static EncodedJSValue constructFromEncoding(JSGlobalObject* lexicalGlobalObject,
result = JSBuffer__bufferFromPointerAndLength(lexicalGlobalObject, reinterpret_cast<const unsigned char*>(view.characters16()), view.length() * 2);
break;
}
default: {
break;
}
}
}
@@ -582,6 +595,9 @@ static inline JSC::EncodedJSValue jsBufferByteLengthFromStringAndEncoding(JSC::J
}
break;
}
default: {
break;
}
}
RELEASE_AND_RETURN(scope, JSC::JSValue::encode(JSC::jsNumber(written)));

View File

@@ -23,7 +23,7 @@
#include "root.h"
#include <JavaScriptCore/JSGlobalObject.h>
#include "wtf/NeverDestroyed.h"
#include <wtf/NeverDestroyed.h>
#include "BufferEncodingType.h"
#include "Buffer.h"

View File

@@ -18,8 +18,6 @@
Boston, MA 02110-1301, USA.
*/
#pragma once
#include "config.h"
#include "JSBufferEncodingType.h"

View File

@@ -1,7 +1,7 @@
#include "JSBufferList.h"
#include "JSBuffer.h"
#include "JavaScriptCore/Lookup.h"
#include "JavaScriptCore/ObjectConstructor.h"
#include <JavaScriptCore/Lookup.h>
#include <JavaScriptCore/ObjectConstructor.h>
#include "ZigGlobalObject.h"
#include "JSDOMOperation.h"
#include "headers.h"
@@ -346,50 +346,42 @@ static inline JSC::EncodedJSValue jsBufferListPrototypeFunction_consumeBody(JSC:
RELEASE_AND_RETURN(throwScope, JSC::JSValue::encode(castedThis->consume(vm, lexicalGlobalObject, n, hasString)));
}
static JSC_DECLARE_HOST_FUNCTION(jsBufferListPrototypeFunction_push);
static JSC_DEFINE_HOST_FUNCTION(jsBufferListPrototypeFunction_push,
JSC_DEFINE_HOST_FUNCTION(jsBufferListPrototypeFunction_push,
(JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
return IDLOperation<JSBufferList>::call<jsBufferListPrototypeFunction_pushBody>(*globalObject, *callFrame, "push");
}
static JSC_DECLARE_HOST_FUNCTION(jsBufferListPrototypeFunction_unshift);
static JSC_DEFINE_HOST_FUNCTION(jsBufferListPrototypeFunction_unshift,
JSC_DEFINE_HOST_FUNCTION(jsBufferListPrototypeFunction_unshift,
(JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
return IDLOperation<JSBufferList>::call<jsBufferListPrototypeFunction_unshiftBody>(*globalObject, *callFrame, "unshift");
}
static JSC_DECLARE_HOST_FUNCTION(jsBufferListPrototypeFunction_shift);
static JSC_DEFINE_HOST_FUNCTION(jsBufferListPrototypeFunction_shift,
JSC_DEFINE_HOST_FUNCTION(jsBufferListPrototypeFunction_shift,
(JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
return IDLOperation<JSBufferList>::call<jsBufferListPrototypeFunction_shiftBody>(*globalObject, *callFrame, "shift");
}
static JSC_DECLARE_HOST_FUNCTION(jsBufferListPrototypeFunction_clear);
static JSC_DEFINE_HOST_FUNCTION(jsBufferListPrototypeFunction_clear,
JSC_DEFINE_HOST_FUNCTION(jsBufferListPrototypeFunction_clear,
(JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
return IDLOperation<JSBufferList>::call<jsBufferListPrototypeFunction_clearBody>(*globalObject, *callFrame, "clear");
}
static JSC_DECLARE_HOST_FUNCTION(jsBufferListPrototypeFunction_first);
static JSC_DEFINE_HOST_FUNCTION(jsBufferListPrototypeFunction_first,
JSC_DEFINE_HOST_FUNCTION(jsBufferListPrototypeFunction_first,
(JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
return IDLOperation<JSBufferList>::call<jsBufferListPrototypeFunction_firstBody>(*globalObject, *callFrame, "first");
}
static JSC_DECLARE_HOST_FUNCTION(jsBufferListPrototypeFunction_concat);
static JSC_DEFINE_HOST_FUNCTION(jsBufferListPrototypeFunction_concat,
JSC_DEFINE_HOST_FUNCTION(jsBufferListPrototypeFunction_concat,
(JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
return IDLOperation<JSBufferList>::call<jsBufferListPrototypeFunction_concatBody>(*globalObject, *callFrame, "concat");
}
static JSC_DECLARE_HOST_FUNCTION(jsBufferListPrototypeFunction_join);
static JSC_DEFINE_HOST_FUNCTION(jsBufferListPrototypeFunction_join,
JSC_DEFINE_HOST_FUNCTION(jsBufferListPrototypeFunction_join,
(JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
return IDLOperation<JSBufferList>::call<jsBufferListPrototypeFunction_joinBody>(*globalObject, *callFrame, "join");
}
static JSC_DECLARE_HOST_FUNCTION(jsBufferListPrototypeFunction_consume);
static JSC_DEFINE_HOST_FUNCTION(jsBufferListPrototypeFunction_consume,
JSC_DEFINE_HOST_FUNCTION(jsBufferListPrototypeFunction_consume,
(JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
return IDLOperation<JSBufferList>::call<jsBufferListPrototypeFunction_consumeBody>(*globalObject, *callFrame, "consume");

View File

@@ -1,7 +1,7 @@
#pragma once
#include "root.h"
#include "wtf/Deque.h"
#include <wtf/Deque.h>
namespace WebCore {
using namespace JSC;
@@ -49,12 +49,12 @@ public:
size_t length() { return m_deque.size(); }
void push(JSC::VM& vm, JSC::JSValue v)
{
m_deque.append(WriteBarrier<Unknown>());
m_deque.append(WriteBarrier<JSC::Unknown>());
m_deque.last().set(vm, this, v);
}
void unshift(JSC::VM& vm, JSC::JSValue v)
{
m_deque.prepend(WriteBarrier<Unknown>());
m_deque.prepend(WriteBarrier<JSC::Unknown>());
m_deque.first().set(vm, this, v);
}
JSC::JSValue shift()
@@ -83,7 +83,7 @@ public:
JSC::JSValue _getString(JSC::VM&, JSC::JSGlobalObject*, size_t);
private:
Deque<WriteBarrier<Unknown>> m_deque;
Deque<WriteBarrier<JSC::Unknown>> m_deque;
};
class JSBufferListPrototype : public JSC::JSNonFinalObject {

View File

@@ -1,24 +1,24 @@
#include "JSBundlerPlugin.h"
#include "headers-handwritten.h"
#include "JavaScriptCore/CatchScope.h"
#include "JavaScriptCore/JSGlobalObject.h"
#include "JavaScriptCore/JSTypeInfo.h"
#include "JavaScriptCore/Structure.h"
#include <JavaScriptCore/CatchScope.h>
#include <JavaScriptCore/JSGlobalObject.h>
#include <JavaScriptCore/JSTypeInfo.h>
#include <JavaScriptCore/Structure.h>
#include "helpers.h"
#include "ZigGlobalObject.h"
#include "JavaScriptCore/JavaScript.h"
#include "JavaScriptCore/JSObjectInlines.h"
#include "wtf/text/WTFString.h"
#include "JavaScriptCore/JSCInlines.h"
#include <JavaScriptCore/JavaScript.h>
#include <JavaScriptCore/JSObjectInlines.h>
#include <wtf/text/WTFString.h>
#include <JavaScriptCore/JSCInlines.h>
#include "JavaScriptCore/ObjectConstructor.h"
#include "JavaScriptCore/SubspaceInlines.h"
#include "JavaScriptCore/RegExpObject.h"
#include "JavaScriptCore/JSPromise.h"
#include <JavaScriptCore/ObjectConstructor.h>
#include <JavaScriptCore/SubspaceInlines.h>
#include <JavaScriptCore/RegExpObject.h>
#include <JavaScriptCore/JSPromise.h>
#include "BunClientData.h"
#include "ModuleLoader.h"
#include "JavaScriptCore/RegularExpression.h"
#include <JavaScriptCore/RegularExpression.h>
#include <JavaScriptCore/LazyProperty.h>
#include <JavaScriptCore/LazyPropertyInlines.h>
#include <JavaScriptCore/VMTrapsInlines.h>
@@ -383,10 +383,10 @@ extern "C" Bun::JSBundlerPlugin* JSBundlerPlugin__create(Zig::GlobalObject* glob
target);
}
extern "C" EncodedJSValue JSBundlerPlugin__runSetupFunction(
extern "C" JSC::EncodedJSValue JSBundlerPlugin__runSetupFunction(
Bun::JSBundlerPlugin* plugin,
EncodedJSValue encodedSetupFunction,
EncodedJSValue encodedConfig)
JSC::EncodedJSValue encodedSetupFunction,
JSC::EncodedJSValue encodedConfig)
{
auto& vm = plugin->vm();
auto scope = DECLARE_CATCH_SCOPE(vm);

View File

@@ -2,9 +2,9 @@
#include "root.h"
#include "headers-handwritten.h"
#include "JavaScriptCore/JSGlobalObject.h"
#include "JavaScriptCore/Strong.h"
#include "JavaScriptCore/RegularExpression.h"
#include <JavaScriptCore/JSGlobalObject.h>
#include <JavaScriptCore/Strong.h>
#include <JavaScriptCore/RegularExpression.h>
#include "helpers.h"
#include <JavaScriptCore/Yarr.h>
#include <JavaScriptCore/Strong.h>

View File

@@ -36,22 +36,22 @@
// In fact, it can make a lot of sense: outside of JSC, this file becomes a kind of umbrella
// header that pulls in most (all?) of the interesting things in JSC.
#include "JavaScriptCore/ExceptionHelpers.h"
#include "JavaScriptCore/GCIncomingRefCountedInlines.h"
#include "JavaScriptCore/HeapInlines.h"
#include "JavaScriptCore/IdentifierInlines.h"
#include "JavaScriptCore/JSArrayBufferViewInlines.h"
#include "JavaScriptCore/JSCJSValueInlines.h"
#include "JavaScriptCore/JSCellInlines.h"
#include "JavaScriptCore/JSFunctionInlines.h"
#include "JavaScriptCore/JSGlobalObjectInlines.h"
#include "JavaScriptCore/JSObjectInlines.h"
#include "JavaScriptCore/JSGlobalProxy.h"
#include "JavaScriptCore/JSString.h"
#include "JavaScriptCore/Operations.h"
#include "JavaScriptCore/SlotVisitorInlines.h"
#include "JavaScriptCore/StrongInlines.h"
#include "JavaScriptCore/StructureInlines.h"
#include "JavaScriptCore/ThrowScope.h"
#include "JavaScriptCore/WeakGCMapInlines.h"
#include "JavaScriptCore/WeakGCSetInlines.h"
#include <JavaScriptCore/ExceptionHelpers.h>
#include <JavaScriptCore/GCIncomingRefCountedInlines.h>
#include <JavaScriptCore/HeapInlines.h>
#include <JavaScriptCore/IdentifierInlines.h>
#include <JavaScriptCore/JSArrayBufferViewInlines.h>
#include <JavaScriptCore/JSCJSValueInlines.h>
#include <JavaScriptCore/JSCellInlines.h>
#include <JavaScriptCore/JSFunctionInlines.h>
#include <JavaScriptCore/JSGlobalObjectInlines.h>
#include <JavaScriptCore/JSObjectInlines.h>
#include <JavaScriptCore/JSGlobalProxy.h>
#include <JavaScriptCore/JSString.h>
#include <JavaScriptCore/Operations.h>
#include <JavaScriptCore/SlotVisitorInlines.h>
#include <JavaScriptCore/StrongInlines.h>
#include <JavaScriptCore/StructureInlines.h>
#include <JavaScriptCore/ThrowScope.h>
#include <JavaScriptCore/WeakGCMapInlines.h>
#include <JavaScriptCore/WeakGCSetInlines.h>

View File

@@ -3,18 +3,18 @@
#include "root.h"
#include "ExceptionOr.h"
#include "JavaScriptCore/AuxiliaryBarrierInlines.h"
#include "JavaScriptCore/HeapInlines.h"
#include "JavaScriptCore/JSArray.h"
#include "JavaScriptCore/JSCJSValueInlines.h"
#include "JavaScriptCore/JSCellInlines.h"
#include "JavaScriptCore/JSObjectInlines.h"
#include "JavaScriptCore/Lookup.h"
#include "JavaScriptCore/ObjectConstructor.h"
#include "JavaScriptCore/SlotVisitorInlines.h"
#include "JavaScriptCore/StructureInlines.h"
#include "JavaScriptCore/WriteBarrier.h"
#include "wtf/Forward.h"
#include "wtf/GetPtr.h"
#include "wtf/Vector.h"
#include <JavaScriptCore/AuxiliaryBarrierInlines.h>
#include <JavaScriptCore/HeapInlines.h>
#include <JavaScriptCore/JSArray.h>
#include <JavaScriptCore/JSCJSValueInlines.h>
#include <JavaScriptCore/JSCellInlines.h>
#include <JavaScriptCore/JSObjectInlines.h>
#include <JavaScriptCore/Lookup.h>
#include <JavaScriptCore/ObjectConstructor.h>
#include <JavaScriptCore/SlotVisitorInlines.h>
#include <JavaScriptCore/StructureInlines.h>
#include <JavaScriptCore/WriteBarrier.h>
#include <wtf/Forward.h>
#include <wtf/GetPtr.h>
#include <wtf/Vector.h>
#include <cstddef>

View File

@@ -26,11 +26,11 @@
#include "JSDOMExceptionHandling.h"
#include "JSDOMPromiseDeferred.h"
#include "JavaScriptCore/ErrorHandlingScope.h"
#include "JavaScriptCore/Exception.h"
#include "JavaScriptCore/ExceptionHelpers.h"
#include "JavaScriptCore/ScriptCallStack.h"
#include "JavaScriptCore/ScriptCallStackFactory.h"
#include <JavaScriptCore/ErrorHandlingScope.h>
#include <JavaScriptCore/Exception.h>
#include <JavaScriptCore/ExceptionHelpers.h>
#include <JavaScriptCore/ScriptCallStack.h>
#include <JavaScriptCore/ScriptCallStackFactory.h>
#include "headers.h"
#include "CachedScript.h"
@@ -200,7 +200,7 @@ void propagateExceptionSlowPath(JSC::JSGlobalObject& lexicalGlobalObject, JSC::T
throwException(&lexicalGlobalObject, throwScope, createDOMException(lexicalGlobalObject, WTFMove(exception)));
}
static EncodedJSValue throwTypeError(JSC::JSGlobalObject& lexicalGlobalObject, JSC::ThrowScope& scope, const String& errorMessage)
static JSC::EncodedJSValue throwTypeError(JSC::JSGlobalObject& lexicalGlobalObject, JSC::ThrowScope& scope, const String& errorMessage)
{
return throwVMTypeError(&lexicalGlobalObject, scope, errorMessage);
}

View File

@@ -27,7 +27,7 @@
#include "ExceptionDetails.h"
#include "ExceptionOr.h"
#include "JavaScriptCore/ThrowScope.h"
#include <JavaScriptCore/ThrowScope.h>
namespace JSC {
class CatchScope;

View File

@@ -1,8 +1,8 @@
#include "root.h"
#include "ZigGeneratedClasses.h"
#include "JavaScriptCore/ObjectConstructor.h"
#include "JavaScriptCore/InternalFunction.h"
#include "JavaScriptCore/FunctionPrototype.h"
#include <JavaScriptCore/ObjectConstructor.h>
#include <JavaScriptCore/InternalFunction.h>
#include <JavaScriptCore/FunctionPrototype.h>
#include "JSDOMFile.h"
using namespace JSC;
@@ -62,7 +62,7 @@ public:
return JSDOMFile__hasInstance(JSValue::encode(object), globalObject, JSValue::encode(value));
}
static EncodedJSValue construct(JSGlobalObject* lexicalGlobalObject, CallFrame* callFrame)
static JSC::EncodedJSValue construct(JSGlobalObject* lexicalGlobalObject, CallFrame* callFrame)
{
Zig::GlobalObject* globalObject = reinterpret_cast<Zig::GlobalObject*>(lexicalGlobalObject);
JSC::VM& vm = globalObject->vm();

View File

@@ -1,5 +1,5 @@
#include "JSDOMGlobalObject.h"
#include "JavaScriptCore/JSCast.h"
#include <JavaScriptCore/JSCast.h>
#include "ZigGlobalObject.h"
namespace WebCore {

View File

@@ -4,10 +4,10 @@
#include "DOMWrapperWorld.h"
#include "JavaScriptCore/HeapInlines.h"
#include "JavaScriptCore/JSGlobalObject.h"
#include "JavaScriptCore/JSObjectInlines.h"
#include "JavaScriptCore/WeakGCMap.h"
#include <JavaScriptCore/HeapInlines.h>
#include <JavaScriptCore/JSGlobalObject.h>
#include <JavaScriptCore/JSObjectInlines.h>
#include <JavaScriptCore/WeakGCMap.h>
#include "ScriptExecutionContext.h"
namespace WebCore {

View File

@@ -33,7 +33,7 @@
// #include "JSDOMWindow.h"
// #include "JSRemoteDOMWindow.h"
// #include "SerializedScriptValue.h"
// #include "JavaScriptCore/Error.h"
// #include <JavaScriptCore/Error.h>
namespace WebCore {

View File

@@ -25,8 +25,8 @@
#include "JSDOMGlobalObject.h"
#include "ZigGlobalObject.h"
#include "NodeConstants.h"
#include "JavaScriptCore/JSDestructibleObject.h"
#include "wtf/SignedPtr.h"
#include <JavaScriptCore/JSDestructibleObject.h>
#include <wtf/SignedPtr.h>
namespace WebCore {
using namespace Zig;

View File

@@ -35,7 +35,7 @@ Structure* cacheDOMStructure(JSDOMGlobalObject& globalObject, Structure* structu
{
auto addToStructures = [](JSDOMStructureMap& structures, JSDOMGlobalObject& globalObject, Structure* structure, const ClassInfo* classInfo) {
ASSERT(!structures.contains(classInfo));
return structures.set(classInfo, WriteBarrier<Structure>(globalObject.vm(), &globalObject, structure)).iterator->value.get();
return structures.set(classInfo, JSC::WriteBarrier<Structure>(globalObject.vm(), &globalObject, structure)).iterator->value.get();
};
if (globalObject.vm().heap.mutatorShouldBeFenced()) {
Locker locker { globalObject.gcLock() };

View File

@@ -3,8 +3,8 @@
#include "helpers.h"
#include "JavaScriptCore/JSObject.h"
#include "JavaScriptCore/ObjectConstructor.h"
#include <JavaScriptCore/JSObject.h>
#include <JavaScriptCore/ObjectConstructor.h>
#include "BunClientData.h"
using namespace JSC;
@@ -15,7 +15,7 @@ namespace Bun {
using namespace WebCore;
JSC_DEFINE_CUSTOM_GETTER(jsGetterEnvironmentVariable, (JSGlobalObject * globalObject, EncodedJSValue thisValue, PropertyName propertyName))
JSC_DEFINE_CUSTOM_GETTER(jsGetterEnvironmentVariable, (JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, PropertyName propertyName))
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
@@ -39,7 +39,7 @@ JSC_DEFINE_CUSTOM_GETTER(jsGetterEnvironmentVariable, (JSGlobalObject * globalOb
return JSValue::encode(result);
}
JSC_DEFINE_CUSTOM_SETTER(jsSetterEnvironmentVariable, (JSGlobalObject * globalObject, EncodedJSValue thisValue, EncodedJSValue value, PropertyName propertyName))
JSC_DEFINE_CUSTOM_SETTER(jsSetterEnvironmentVariable, (JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::EncodedJSValue value, PropertyName propertyName))
{
VM& vm = globalObject->vm();
JSC::JSObject* object = JSValue::decode(thisValue).getObject();
@@ -50,7 +50,7 @@ JSC_DEFINE_CUSTOM_SETTER(jsSetterEnvironmentVariable, (JSGlobalObject * globalOb
return true;
}
JSC_DEFINE_CUSTOM_GETTER(jsTimeZoneEnvironmentVariableGetter, (JSGlobalObject * globalObject, EncodedJSValue thisValue, PropertyName propertyName))
JSC_DEFINE_CUSTOM_GETTER(jsTimeZoneEnvironmentVariableGetter, (JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, PropertyName propertyName))
{
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
@@ -81,7 +81,7 @@ JSC_DEFINE_CUSTOM_GETTER(jsTimeZoneEnvironmentVariableGetter, (JSGlobalObject *
// In Node.js, the "TZ" environment variable is special.
// Setting it automatically updates the timezone.
// We also expose an explicit setTimeZone function in bun:jsc
JSC_DEFINE_CUSTOM_SETTER(jsTimeZoneEnvironmentVariableSetter, (JSGlobalObject * globalObject, EncodedJSValue thisValue, EncodedJSValue value, PropertyName propertyName))
JSC_DEFINE_CUSTOM_SETTER(jsTimeZoneEnvironmentVariableSetter, (JSGlobalObject * globalObject, JSC::EncodedJSValue thisValue, JSC::EncodedJSValue value, PropertyName propertyName))
{
VM& vm = globalObject->vm();
JSC::JSObject* object = JSValue::decode(thisValue).getObject();
@@ -113,7 +113,7 @@ JSValue createEnvironmentVariablesMap(Zig::GlobalObject* globalObject)
VM& vm = globalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
size_t max = 768;
constexpr size_t max = 768;
ZigString names[max];
size_t count = Bun__getEnvNames(globalObject, names, max);
JSC::JSObject* object = nullptr;

View File

@@ -26,8 +26,8 @@
#include "root.h"
#include "JSFFIFunction.h"
#include "JavaScriptCore/JSCJSValueInlines.h"
#include "JavaScriptCore/VM.h"
#include <JavaScriptCore/JSCJSValueInlines.h>
#include <JavaScriptCore/VM.h>
#include "ZigGlobalObject.h"
#include <JavaScriptCore/DOMJITAbstractHeap.h>

View File

@@ -5,12 +5,12 @@ class GlobalObject;
}
#include "root.h"
#include "JavaScriptCore/JSFunction.h"
#include "JavaScriptCore/VM.h"
#include <JavaScriptCore/JSFunction.h>
#include <JavaScriptCore/VM.h>
#include "headers-handwritten.h"
#include "BunClientData.h"
#include "JavaScriptCore/CallFrame.h"
#include <JavaScriptCore/CallFrame.h>
namespace JSC {
class JSGlobalObject;

View File

@@ -4,16 +4,16 @@
#include <JavaScriptCore/JSPromise.h>
#include "ZigGlobalObject.h"
#include <JavaScriptCore/InternalFunction.h>
#include "JavaScriptCore/Completion.h"
#include "JavaScriptCore/ObjectConstructor.h"
#include <JavaScriptCore/Completion.h>
#include <JavaScriptCore/ObjectConstructor.h>
#include "ExtendedDOMClientIsoSubspaces.h"
#include "ExtendedDOMIsoSubspaces.h"
#include "BunClientData.h"
#include "JavaScriptCore/LazyProperty.h"
#include "JavaScriptCore/JSCJSValueInlines.h"
#include "JavaScriptCore/JSInternalPromise.h"
#include "JavaScriptCore/LazyPropertyInlines.h"
#include "JavaScriptCore/VMTrapsInlines.h"
#include <JavaScriptCore/LazyProperty.h>
#include <JavaScriptCore/JSCJSValueInlines.h>
#include <JavaScriptCore/JSInternalPromise.h>
#include <JavaScriptCore/LazyPropertyInlines.h>
#include <JavaScriptCore/VMTrapsInlines.h>
#include <JavaScriptCore/Weak.h>
#include <JavaScriptCore/GetterSetter.h>
#include <JavaScriptCore/WeakMapImpl.h>
@@ -67,22 +67,22 @@ JSC_DECLARE_HOST_FUNCTION(jsMockFunctionWithImplementationCleanup);
JSC_DECLARE_HOST_FUNCTION(jsMockFunctionWithImplementation);
// This is a stub. Exists so that the same code can be run in Jest
extern "C" EncodedJSValue JSMock__jsUseFakeTimers(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame)
extern "C" JSC::EncodedJSValue JSMock__jsUseFakeTimers(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame)
{
return JSValue::encode(callFrame->thisValue());
}
extern "C" EncodedJSValue JSMock__jsUseRealTimers(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame)
extern "C" JSC::EncodedJSValue JSMock__jsUseRealTimers(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame)
{
globalObject->overridenDateNow = -1;
return JSValue::encode(callFrame->thisValue());
}
extern "C" EncodedJSValue JSMock__jsNow(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame)
extern "C" JSC::EncodedJSValue JSMock__jsNow(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame)
{
return JSValue::encode(jsNumber(globalObject->jsDateNow()));
}
extern "C" EncodedJSValue JSMock__jsSetSystemTime(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame)
extern "C" JSC::EncodedJSValue JSMock__jsSetSystemTime(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callFrame)
{
JSValue argument0 = callFrame->argument(0);
@@ -169,13 +169,13 @@ public:
}
// either a function or a return value, depends on kind
mutable JSC::WriteBarrier<Unknown> underlyingValue;
mutable JSC::WriteBarrier<JSC::Unknown> underlyingValue;
// a combination of a pointer to the next implementation and a flag indicating if this is a once implementation
// - undefined - no next value
// - jsNumber(1) - no next value + is a once implementation
// - JSMockImplementation - next value + is a once implementation
mutable JSC::WriteBarrier<Unknown> nextValueOrSentinel;
mutable JSC::WriteBarrier<JSC::Unknown> nextValueOrSentinel;
DECLARE_EXPORT_INFO;
DECLARE_VISIT_CHILDREN;
@@ -561,13 +561,13 @@ extern "C" void JSMock__resetSpies(Zig::GlobalObject* globalObject)
globalObject->mockModule.activeSpies.clear();
}
extern "C" EncodedJSValue JSMock__jsRestoreAllMocks(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe)
extern "C" JSC::EncodedJSValue JSMock__jsRestoreAllMocks(JSC::JSGlobalObject* globalObject, JSC::CallFrame* callframe)
{
JSMock__resetSpies(jsCast<Zig::GlobalObject*>(globalObject));
return JSValue::encode(jsUndefined());
}
extern "C" EncodedJSValue JSMock__jsSpyOn(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callframe)
extern "C" JSC::EncodedJSValue JSMock__jsSpyOn(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callframe)
{
auto& vm = lexicalGlobalObject->vm();
auto scope = DECLARE_THROW_SCOPE(vm);
@@ -1002,7 +1002,7 @@ JSC_DEFINE_CUSTOM_GETTER(jsMockFunctionGetter_protoImpl, (JSC::JSGlobalObject *
return JSValue::encode(jsUndefined());
}
extern "C" EncodedJSValue JSMock__jsMockFn(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callframe)
extern "C" JSC::EncodedJSValue JSMock__jsMockFn(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callframe)
{
auto& vm = lexicalGlobalObject->vm();
auto* globalObject = jsCast<Zig::GlobalObject*>(lexicalGlobalObject);
@@ -1036,7 +1036,7 @@ extern "C" EncodedJSValue JSMock__jsMockFn(JSC::JSGlobalObject* lexicalGlobalObj
return JSValue::encode(thisObject);
}
extern "C" EncodedJSValue JSMockFunction__getCalls(EncodedJSValue encodedValue)
extern "C" JSC::EncodedJSValue JSMockFunction__getCalls(EncodedJSValue encodedValue)
{
JSValue value = JSValue::decode(encodedValue);
if (auto* mock = tryJSDynamicCast<JSMockFunction*>(value)) {
@@ -1045,7 +1045,7 @@ extern "C" EncodedJSValue JSMockFunction__getCalls(EncodedJSValue encodedValue)
return JSValue::encode({});
}
extern "C" EncodedJSValue JSMockFunction__getReturns(EncodedJSValue encodedValue)
extern "C" JSC::EncodedJSValue JSMockFunction__getReturns(EncodedJSValue encodedValue)
{
JSValue value = JSValue::decode(encodedValue);
if (auto* mock = tryJSDynamicCast<JSMockFunction*>(value)) {

Some files were not shown because too many files have changed in this diff Show More