diff --git a/.github/workflows/integrate.yml b/.github/workflows/integrate.yml index 4452d61..c7ebe95 100644 --- a/.github/workflows/integrate.yml +++ b/.github/workflows/integrate.yml @@ -20,104 +20,74 @@ jobs: steps: - uses: holepunchto/actions/node-base@v1 - run: npm run lint - apple: + test: strategy: matrix: include: - - os: macos-26-intel + - os: ubuntu-22.04 + platform: linux + arch: x64 + flags: --sanitize address + - os: ubuntu-22.04-arm + platform: linux + arch: arm64 + flags: --sanitize address + - os: ubuntu-24.04 + platform: android + arch: x64 + flags: -D ANDROID_STL=c++_static + - os: ubuntu-24.04 + platform: android + arch: ia32 + flags: -D ANDROID_STL=c++_static + - os: ubuntu-24.04 + platform: android + arch: arm64 + flags: -D ANDROID_STL=c++_static + - os: ubuntu-24.04 + platform: android + arch: arm + flags: -D ANDROID_STL=c++_static + - os: macos-15-intel platform: darwin arch: x64 - - os: macos-26 + flags: --sanitize address + - os: macos-15 platform: darwin arch: arm64 - - os: macos-26 + flags: --sanitize address + - os: macos-15 platform: ios arch: arm64 - - os: macos-26 + - os: macos-15 platform: ios arch: arm64 tags: -simulator flags: --simulator - - os: macos-26 + - os: macos-15 platform: ios arch: x64 tags: -simulator flags: --simulator - runs-on: ${{ matrix.os }} - name: Test / ${{ matrix.platform }}-${{ matrix.arch }}${{ matrix.tags }} - steps: - - uses: holepunchto/actions/checkout@v1 - - uses: holepunchto/actions/setup-node@v1 - - run: npm install --global bare-make - - run: npm install - - run: bare-make generate --platform ${{ matrix.platform }} --arch ${{ matrix.arch }} ${{ matrix.flags }} --debug - - run: bare-make build - - run: bare-make test - if: ${{ matrix.platform == 'darwin' }} - android: - strategy: - matrix: - include: - - os: ubuntu-24.04 - platform: android - runs-on: ${{ matrix.os }} - name: Test / ${{ matrix.platform }} - steps: - - uses: holepunchto/actions/checkout@v1 - - uses: holepunchto/actions/setup-node@v1 - - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 - with: - distribution: temurin - java-version: 21 - - run: npm install --global cmake-runtime ninja-runtime - - run: npm install - - run: ./gradlew aR - linux: - strategy: - matrix: - include: - - os: ubuntu-22.04 - platform: linux - arch: x64 - - os: ubuntu-22.04-arm - platform: linux - arch: arm64 - runs-on: ${{ matrix.os }} - name: Test / ${{ matrix.platform }}-${{ matrix.arch }} - steps: - - uses: holepunchto/actions/checkout@v1 - - uses: holepunchto/actions/setup-node@v1 - - run: | - wget https://apt.llvm.org/llvm.sh - chmod +x llvm.sh - sudo ./llvm.sh 22 - if: ${{ matrix.platform == 'linux' }} - - run: npm install --global bare-make - - run: npm install - - run: bare-make generate --platform ${{ matrix.platform }} --arch ${{ matrix.arch }} --debug - - run: bare-make build - - run: bare-make test - windows: - strategy: - matrix: - include: - os: windows-2022 platform: win32 arch: x64 + flags: --sanitize address - os: windows-11-arm platform: win32 arch: arm64 runs-on: ${{ matrix.os }} - name: Test / ${{ matrix.platform }}-${{ matrix.arch }} + name: Test / ${{ matrix.platform }}-${{ matrix.arch }}${{ matrix.tags }} steps: - - uses: holepunchto/actions/checkout@v1 - - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + - uses: holepunchto/actions/node-base@v1 + - uses: holepunchto/actions/compile-prebuilds@v1 with: - node-version: lts/* - - run: choco install llvm --version 22.1.8 --force - - run: choco install nasm - - run: npm install --global bare-make - - run: npm install - - run: bare-make generate --platform ${{ matrix.platform }} --arch ${{ matrix.arch }} --debug - - run: bare-make build + platform: ${{ matrix.platform }} + arch: ${{ matrix.arch }} + flags: --debug ${{ matrix.flags }} + tags: ${{ matrix.tags}} - run: bare-make test + env: + ASAN_OPTIONS: detect_leaks=${{ matrix.platform == 'win32' && '0' || '1' }} + LSAN_OPTIONS: suppressions=test/leaks.txt + if: ${{ matrix.platform == 'linux' || matrix.platform == 'darwin' || matrix.platform == 'win32' }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 3c0c649..d9a6ba2 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -4,199 +4,11 @@ on: tags: - v* permissions: - contents: read + contents: write jobs: - apple: - strategy: - matrix: - include: - - os: macos-26 - platform: darwin - arch: x64 - - os: macos-26 - platform: darwin - arch: x64 - tags: -javascriptcore - flags: -D BARE_ENGINE=github:holepunchto/libjsc - - os: macos-26 - platform: darwin - arch: arm64 - - os: macos-26 - platform: darwin - arch: arm64 - tags: -javascriptcore - flags: -D BARE_ENGINE=github:holepunchto/libjsc - - os: macos-26 - platform: ios - arch: arm64 - - os: macos-26 - platform: ios - arch: arm64 - tags: -javascriptcore - flags: -D BARE_ENGINE=github:holepunchto/libjsc -D APPLE_CLANG=ON - - os: macos-26 - platform: ios - arch: arm64 - tags: -simulator - flags: --simulator - - os: macos-26 - platform: ios - arch: arm64 - tags: -simulator-javascriptcore - flags: --simulator -D BARE_ENGINE=github:holepunchto/libjsc -D APPLE_CLANG=ON - - os: macos-26 - platform: ios - arch: x64 - tags: -simulator - flags: --simulator - - os: macos-26 - platform: ios - arch: x64 - tags: -simulator-javascriptcore - flags: --simulator -D BARE_ENGINE=github:holepunchto/libjsc -D APPLE_CLANG=ON - runs-on: ${{ matrix.os }} - name: Build / ${{ matrix.platform }}-${{ matrix.arch }}${{ matrix.tags }} - steps: - - uses: holepunchto/actions/checkout@v1 - - uses: holepunchto/actions/setup-node@v1 - - run: npm install --global bare-make - - run: npm install - - run: bare-make generate --platform ${{ matrix.platform }} --arch ${{ matrix.arch }} --with-debug-symbols ${{ matrix.flags }} - - run: bare-make build - - run: tar -cvf build/apple/BareKit.framework.tar -C build/apple BareKit.framework - - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: ${{ matrix.platform }}-${{ matrix.arch }}${{ matrix.tags }} - path: build/apple/*.framework.tar - android: - strategy: - matrix: - include: - - os: ubuntu-24.04 - platform: android - runs-on: ${{ matrix.os }} - name: Build / ${{ matrix.platform }} - steps: - - uses: holepunchto/actions/checkout@v1 - - uses: holepunchto/actions/setup-node@v1 - - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5.7.0 - with: - distribution: temurin - java-version: 21 - - run: npm install --global cmake-runtime ninja-runtime - - run: npm install - - run: ./gradlew aR - - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: ${{ matrix.platform }} - path: android/build/outputs/aar/*-release.aar - linux: - strategy: - matrix: - include: - - os: ubuntu-22.04 - platform: linux - arch: x64 - - os: ubuntu-22.04-arm - platform: linux - arch: arm64 - runs-on: ${{ matrix.os }} - name: Build / ${{ matrix.platform }}-${{ matrix.arch }} - steps: - - uses: holepunchto/actions/checkout@v1 - - uses: holepunchto/actions/setup-node@v1 - - run: | - wget https://apt.llvm.org/llvm.sh - chmod +x llvm.sh - sudo ./llvm.sh 22 - if: ${{ matrix.platform == 'linux' }} - - run: npm install --global bare-make - - run: npm install - - run: bare-make generate --platform ${{ matrix.platform }} --arch ${{ matrix.arch }} --with-debug-symbols - - run: bare-make build - - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: ${{ matrix.platform }}-${{ matrix.arch }} - path: build/linux/*.so - windows: - strategy: - matrix: - include: - - os: windows-2022 - platform: win32 - arch: x64 - - os: windows-11-arm - platform: win32 - arch: arm64 - runs-on: ${{ matrix.os }} - name: Build / ${{ matrix.platform }}-${{ matrix.arch }} - steps: - - uses: holepunchto/actions/checkout@v1 - - uses: holepunchto/actions/setup-node@v1 - - run: choco install llvm --version 22.1.8 --force - - run: choco install nasm - - run: npm install --global bare-make - - run: npm install - - run: bare-make generate --platform ${{ matrix.platform }} --arch ${{ matrix.arch }} --with-debug-symbols - - run: bare-make build - - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: ${{ matrix.platform }}-${{ matrix.arch }} - path: | - build/win32/bare-kit.dll - build/win32/bare-kit.lib - build/win32/bare-kit.def - merge: - runs-on: macos-latest - needs: - - apple - - android - - linux - - windows - name: Merge - steps: - - uses: holepunchto/actions/checkout@v1 - with: - sparse-checkout: | - prebuilds/Makefile - - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - path: prebuilds - - run: make - working-directory: prebuilds - - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: prebuilds - path: | - prebuilds/apple/BareKit.xcframework - prebuilds/apple-javascriptcore/BareKit.xcframework - prebuilds/darwin/BareKit.xcframework - prebuilds/darwin-javascriptcore/BareKit.xcframework - prebuilds/ios/BareKit.xcframework - prebuilds/ios-javascriptcore/BareKit.xcframework - prebuilds/android/bare-kit - prebuilds/linux/x64/libbare-kit.so - prebuilds/linux/arm64/libbare-kit.so - prebuilds/win32/x64/bare-kit.dll - prebuilds/win32/x64/bare-kit.lib - prebuilds/win32/x64/bare-kit.def - prebuilds/win32/arm64/bare-kit.dll - prebuilds/win32/arm64/bare-kit.lib - prebuilds/win32/arm64/bare-kit.def - retention-days: 5 publish: - permissions: - contents: write runs-on: ubuntu-latest - needs: merge name: Publish steps: - uses: holepunchto/actions/checkout@v1 - - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: prebuilds - skip-decompress: true - - run: gh release create "$TAG" prebuilds.zip --generate-notes - env: - GH_TOKEN: ${{ github.token }} - TAG: ${{ github.ref_name }} + - uses: holepunchto/actions/create-github-release@v1 diff --git a/.gitignore b/.gitignore index 8596000..a94cb24 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,5 @@ -.gradle/ -.cxx/ .idea/ build/ node_modules/ -local.properties *.bundle.h *.d diff --git a/CMakeLists.txt b/CMakeLists.txt index 91abdee..d55712d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7,31 +7,13 @@ find_package(cmake-napi REQUIRED PATHS node_modules/cmake-napi) project(bare_kit LANGUAGES C CXX VERSION 2.5.5) -include(overrides.cmake) - if(APPLE) enable_language(OBJC) endif() -fetch_package("github:holepunchto/bare@1.33.5" SOURCE_DIR bare) - -add_subdirectory(shared) - -if(APPLE) - add_subdirectory(apple) -endif() - -if(ANDROID) - add_subdirectory(android) -endif() +fetch_package("github:holepunchto/bare@1.36.1") -if(LINUX) - add_subdirectory(linux) -endif() - -if(WIN32) - add_subdirectory(win32) -endif() +add_subdirectory(src) if(PROJECT_IS_TOP_LEVEL) enable_testing() diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 832abaa..0000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1,45 +0,0 @@ -# CONTRIBUTING - -## Dependencies - -First, `bare-make` should be installed globally: - -```bash -npm i -g bare-make -``` - -Then, install the dependencies: - -```bash -npm i -``` - -## iOS - -### Build - -Generate the project: - -```bash -bare-make generate --platform ios --arch arm64 --simulator -``` - -Build the project: - -```bash -bare-make build -``` - -### Test - -Start the simulator and run: - -```bash -xcrun simctl spawn "" ./build/test/apple/worklet.app/worklet -``` - -For instance for the iPhone 15: - -```bash -xcrun simctl spawn "iPhone 15" ./build/test/apple/worklet.app/worklet -``` diff --git a/README.md b/README.md index 18a86cc..aae65fd 100644 --- a/README.md +++ b/README.md @@ -1,317 +1,133 @@ # bare-kit -Bare for native application development. The kit provides a web worker-like API to start and manage isolated Bare threads, called worklets[^1], that expose an IPC abstraction with bindings for various languages. +Bare Kit is a C library that embeds Bare in a host application, running each JavaScript entry point in an isolated thread, called a worklet, with an in-process IPC channel to the host. It aims to be a "one size fits most" embedder that language bindings build on rather than embedding Bare themselves. -[^1]: This term was chosen to avoid ambiguity with worker threads as implemented by . +## Usage -## Worklet +```c +#include +#include +#include +#include -In this section, we will learn how to create a worklet both iOS and Android. +static uv_sem_t exited; -### iOS +static void +on_worklet_exit(int exit_code, void *data) { + printf("Exited with code %d\n", exit_code); -This is a basic example of how to create a worklet in Objective-C: - -```objc -#import -#import - -int -main() { - BareWorkletConfiguration *options = [BareWorkletConfiguration defaultWorkletConfiguration]; - options.memoryLimit = 1024 * 1024 * 24; // 24 MiB - - BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:options]; - - NSString *source = @"console.log('hello from the worklet')"; - - [worklet start:@"/app.js" source:[source dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; - - [[NSRunLoop currentRunLoop] run]; + uv_sem_post(&exited); } -``` - -You can create a `BareWorkletConfiguration` to optionally set the memory limit or attach assets. This step is optional. - -The configuration is then passed to the `BareWorklet`, which represents the running worklet instance. - -Available actions on a worklet include: - -- `[worklet start]`: starts the worklet -- `[worklet suspend]`: suspends the execution of the worklet -- `[worklet suspendWithLinger]`: suspends the worklet for a specified duration; the linger integer (in milliseconds) defines how long to keep the process alive before it fully exits -- `[worklet resume]`: resumes a suspended worklet -- `[worklet terminate]`: terminates the worklet -> [!TIP] -> For a full API reference, see [`apple/BareKit/BareKit.h`](apple/BareKit/BareKit.h). +static void +on_readable(bare_ipc_poll_t *poll, int events) { + bare_ipc_t *ipc = bare_ipc_poll_get_ipc(poll); -### Android + char data[BARE_IPC_READ_BUFFER_SIZE]; -This is a basic example of how to create a worklet in Java: + int len = bare_ipc_read(ipc, data, sizeof(data)); -```java -import to.holepunch.bare.kit.Worklet; -import java.nio.charset.StandardCharsets; - -Worklet.Options options = new Worklet.Options() - .memoryLimit(24 * 1024 * 1024); // 24 MiB - -Worklet worklet = new Worklet(options); - -String source = "console.log('hello from the worklet')"; - -worklet.start("/app.js", source, StandardCharsets.UTF_8, null); -``` - -You can create a `Worklet.Options` to optionally set the memory limit or attach assets. This step is optional. - -The configuration is then passed to the `Worklet`, which represents the running worklet instance. - -Available actions on a worklet include: - -- `worklet.start()`: starts the worklet -- `worklet.suspend()`: suspends the execution of the worklet -- `worklet.suspend(linger)`: suspends the worklet for a specified duration; the linger integer (in milliseconds) defines how long to keep the process alive before it fully exits -- `worklet.resume()`: resumes a suspended worklet -- `worklet.terminate()`: terminates the worklet - -> [!TIP] -> For a full API reference, see [`android/src/main/java/to/holepunch/bare/kit/Worklet.java`](android/src/main/java/to/holepunch/bare/kit/Worklet.java). - -## IPC - -Bare Kit provides an IPC (Inter-Process Communication) abstraction that allows communication between the main application and worklets. The IPC interface provides both synchronous and asynchronous read/write operations with callback-based event handling. - -> [!IMPORTANT] -> IPC operations are **non-blocking** regardless of whether you use synchronous or asynchronous APIs. They may return partial results (e.g., writing fewer bytes than requested) and require polling to complete the operation. - -### iOS + if (len > 0) printf("%.*s\n", len, data); + else if (len == 0) bare_ipc_close(ipc); +} -#### Polling IPC +int +main() { + uv_sem_init(&exited, 0); -The `BareIPC` class provides these methods for polling IPC: + bare_worklet_options_t options = { + .version = 0, + .memory_limit = 24 * 1024 * 1024, + }; -- `ipc.readable`: callback property for when data is available to read -- `ipc.writable`: callback property for when data can be written -- `[ipc read]`: synchronously reads available data, returns `nil` if no data is available -- `[ipc write:data]`: synchronously writes data, returns the number of bytes written + bare_worklet_t *worklet; + bare_worklet_create(&options, &worklet); -```objc -#import -#import + bare_worklet_on_exit(worklet, on_worklet_exit, NULL); -int -main() { - BareWorkletConfiguration *options = [BareWorkletConfiguration defaultWorkletConfiguration]; - options.memoryLimit = 1024 * 1024 * 24; // 24 MiB + bare_ipc_t *ipc; + bare_ipc_create(worklet, &ipc); - BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:options]; + bare_ipc_poll_t *poll; + bare_ipc_poll_create(ipc, &poll); + bare_ipc_poll_start(poll, bare_ipc_readable, on_readable); - NSString *source = @"console.log('hello from the worklet')"; - [worklet start:@"/app.js" source:[source dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; + char *code = "Bare.IPC.on('data', (data) => Bare.IPC.end(data))"; - BareIPC *ipc = [[BareIPC alloc] initWithWorklet:worklet]; + bare_worklet_start(worklet, "/app.js", code, strlen(code), 0, NULL); - // Set up readable callback - ipc.readable = ^(BareIPC *ipc) { - NSData *data = [ipc read]; - if (data) { - NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - NSLog(@"Received: %@", message); - } - }; + bare_ipc_write(ipc, "Hello world", 11); - // Set up writable callback and write data - NSString *message = @"Hello from main thread"; - NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding]; + uv_sem_wait(&exited); - ipc.writable = ^(BareIPC *ipc) { - NSInteger written = [ipc write:data]; - NSLog(@"Written %ld bytes", (long)written); - ipc.writable = nil; // Clear the callback after writing - }; + bare_ipc_poll_destroy(poll); + bare_ipc_destroy(ipc); + bare_worklet_destroy(worklet); - [[NSRunLoop currentRunLoop] run]; + bare_worklet_teardown(); } ``` -> [!NOTE] -> On iOS, IPC callbacks run on a dedicated queue, so callers must be mindful of synchronization when accessing shared resources from these callbacks. +The worklet echoes what the host writes and then ends its side of the IPC. The host prints the echo, closes its own side once it reads the end of the stream, and waits for the worklet to exit. -#### Async IPC +If `source` is `NULL`, the contents of `filename` are instead read at runtime. -The `BareIPC` class provides these methods for async IPC: +The API is documented in [`include/bare-kit.h`](include/bare-kit.h). -- `[ipc read:completion]`: asynchronously reads data with a completion callback -- `[ipc write:data completion:]`: asynchronously writes data with a completion callback +## Resources -```objc -#import -#import +A relative `filename` names a resource of the application, so a bundle can reference assets that ship with the application. On Apple platforms, it resolves against the resources of the application bundle, which extensions share with their application. On Android, it resolves against the code cache directory, and the resources listed in `.assets`, one `/` per line, are extracted there from the APK before `.bundle` first runs: -int -main() { - BareWorkletConfiguration *options = [BareWorkletConfiguration defaultWorkletConfiguration]; - options.memoryLimit = 1024 * 1024 * 24; // 24 MiB - - BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:options]; - BareIPC *ipc = [[BareIPC alloc] initWithWorklet:worklet]; - - NSString *source = @"console.log('hello from the worklet')"; - [worklet start:@"/app.js" source:[source dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; - - // Read data asynchronously - [ipc read:^(NSData *data, NSError *error) { - if (error) { - NSLog(@"Read error: %@", error); - } else if (data) { - NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - NSLog(@"Received: %@", message); - } - }]; - - // Write data asynchronously - NSString *message = @"Hello from main thread"; - NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding]; - [ipc write:data completion:^(NSError *error) { - if (error) { - NSLog(@"Write error: %@", error); - } else { - NSLog(@"Message sent successfully"); - } - }]; - - [[NSRunLoop currentRunLoop] run]; -} +``` +bare-stow.bundle +bare-stow.assets +bare-stow/node_modules/a/asset.txt ``` -**Utility methods** - -- `[ipc close]`: closes the IPC connection - -> [!TIP] -> For a full API reference, see [`apple/BareKit/BareKit.h`](apple/BareKit/BareKit.h). - -### Android - -#### Polling IPC +## Lifecycle -The `IPC` class provides these methods for polling IPC: +`bare_worklet_start()` runs the worklet on a thread of its own. The worklet exits when its event loop runs out of work, when it calls `Bare.exit()`, or when the host calls `bare_worklet_terminate()`. An open IPC keeps the worklet running until both the worklet and the host have ended their side of it, just like a pipe would. -- `ipc.readable(callback)`: sets a callback for when data is available to read -- `ipc.writable(callback)`: sets a callback for when data can be written -- `ipc.read()`: synchronously reads available data, returns `null` if no data is available -- `ipc.write(data)`: synchronously writes data, returns the number of bytes written +Once the worklet has exited and torn down, the exit callback is called exactly once on the worklet thread with the exit code. This also happens when the host destroys a running worklet, so the callback is the place to release whatever the host associated with it. By then, any IPC of the worklet has reached the end of the stream, and suspending, resuming, waking up, or terminating the worklet does nothing. -```java -import to.holepunch.bare.kit.Worklet; -import to.holepunch.bare.kit.IPC; -import java.nio.charset.StandardCharsets; -import java.nio.ByteBuffer; +`bare_worklet_destroy()` never blocks. It terminates the worklet if it is still running and hands it over to tear itself down, and it may be called before or after destroying its IPC. -Worklet.Options options = new Worklet.Options() - .memoryLimit(24 * 1024 * 1024); // 24 MiB +The worklets of a process share a single JavaScript platform, which can only be created once. A host that is done with Bare Kit for good calls `bare_worklet_teardown()` once its worklets have been terminated or destroyed: it waits for any worklet still tearing down and then destroys the platform, after which no worklet may start. A host that runs worklets for as long as it lives need not call it. -Worklet worklet = new Worklet(options); -IPC ipc = new IPC(worklet); +## IPC -String source = "console.log('hello from the worklet')"; -worklet.start("/app.js", source, StandardCharsets.UTF_8, null); +The worklet side of the IPC is a duplex stream available as `Bare.IPC`. The host side is read and written with `bare_ipc_read()` and `bare_ipc_write()`, which never block: they return `bare_ipc_would_block` when there is nothing to read or no room to write. A poll calls the host back when the IPC becomes readable or writable. Ending either side is a half-close, so the other side reads the end of the stream but may keep writing. - // Set up readable callback - ipc.readable(() -> { - ByteBuffer data = ipc.read(); - if (data != null) { - byte[] bytes = new byte[data.remaining()]; - data.get(bytes); - String message = new String(bytes, StandardCharsets.UTF_8); - System.out.println("Received: " + message); - } - }); +Poll callbacks run on a thread owned by the IPC rather than the thread that started the poll, on every platform. A callback may stop or destroy its poll, or the IPC itself. - // Set up writable callback and write data - String message = "Hello from main thread"; - ByteBuffer data = ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8)); +## Suspension - ipc.writable(() -> { - int written = ipc.write(data); - System.out.println("Written " + written + " bytes"); - ipc.writable(null); // Clear the callback after writing - }); -``` +`bare_worklet_suspend()`, `bare_worklet_resume()`, and `bare_worklet_wakeup()` forward the lifecycle of the host application to the worklet, which observes them as the `suspend`, `resume`, and `wakeup` events of `Bare`. A suspension may linger for a number of milliseconds before the worklet goes idle. On iOS, the worklet holds a background task for as long as it lingers. -#### Async IPC - -The `IPC` class provides these methods for async IPC: - -- `ipc.read(callback)`: asynchronously reads data with a callback -- `ipc.write(data, callback)`: asynchronously writes data with a callback - -```java -import to.holepunch.bare.kit.Worklet; -import to.holepunch.bare.kit.IPC; -import java.nio.charset.StandardCharsets; -import java.nio.ByteBuffer; - -Worklet.Options options = new Worklet.Options() - .memoryLimit(24 * 1024 * 1024); // 24 MiB - -Worklet worklet = new Worklet(options); -IPC ipc = new IPC(worklet); - -String source = "console.log('hello from the worklet')"; -worklet.start("/app.js", source, StandardCharsets.UTF_8, null); - -// Read data asynchronously -ipc.read((data, exception) -> { - if (exception != null) { - System.err.println("Read error: " + exception.getMessage()); - } else if (data != null) { - byte[] bytes = new byte[data.remaining()]; - data.get(bytes); - String message = new String(bytes, StandardCharsets.UTF_8); - System.out.println("Received: " + message); - } -}); - -// Write data asynchronously -String message = "Hello from main thread"; -ByteBuffer data = ByteBuffer.wrap(message.getBytes(StandardCharsets.UTF_8)); -ipc.write(data, (exception) -> { - if (exception != null) { - System.err.println("Write error: " + exception.getMessage()); - } else { - System.out.println("Message sent successfully"); - } -}); -``` +## Addons -**Utility methods** +The native addons of a worklet resolve the symbols of Bare from the host process. This works as is when the host links or loads the shared library. Otherwise: -- `ipc.close()`: closes the IPC connection +- A host that links Bare Kit statically into an executable must export its symbols, such as with `ENABLE_EXPORTS` and, on Windows, `WINDOWS_EXPORT_ALL_SYMBOLS` in CMake. +- A host that links Bare Kit statically into a shared library must keep its symbols exported. On Android, it must also link with `-z global`. -> [!TIP] -> For a full API reference, see [`android/src/main/java/to/holepunch/bare/kit/IPC.java`](android/src/main/java/to/holepunch/bare/kit/IPC.java). +Addons may bind to the wrong symbols if the process already exports libuv, V8, or Node-API, as Node.js and Electron do, or holds more than one copy of Bare Kit. ## Error handling -A worklet runs as a thread inside the host process, so it follows Bare's default handling of uncaught errors: an uncaught exception or unhandled promise rejection in worklet JavaScript is printed to `stderr` and the process is aborted. Because the worklet shares the host's process, this takes the **host** down with it. This is by design. +A worklet runs as a thread inside the host process, so it follows Bare's default handling of uncaught errors: an uncaught exception or unhandled promise rejection in the worklet is printed and the process is aborted. Because the worklet shares the process of the host, this takes the host down with it. This is by design. -To keep a worklet error from aborting the host, register an `uncaughtException` (and/or `unhandledRejection`) listener inside the worklet. Adding a listener overrides the default abort and lets the worklet decide how to respond: +To keep a worklet error from aborting the host, register an `uncaughtException` and an `unhandledRejection` listener inside the worklet, and report the error to the host before exiting: ```js Bare.on('uncaughtException', (err) => { - // The host no longer aborts. Report the error to the host (for example over - // Bare.IPC) and exit or recover as appropriate. - console.error(err) + Bare.IPC.write(String(err)) + + Bare.exit(1) }) ``` -> [!IMPORTANT] -> The handler runs inside the worklet, not in the host - the host cannot catch a worklet exception directly. Surface it yourself, for example by sending a message over IPC from the handler before the worklet exits. - -See Bare's [`uncaughtException`](https://github.com/holepunchto/bare#bareonuncaughtexception-err) and [`unhandledRejection`](https://github.com/holepunchto/bare#bareonunhandledrejection-reason-promise) for the underlying behavior. +See [`uncaughtException`](https://github.com/holepunchto/bare#bareonuncaughtexception-err) and [`unhandledRejection`](https://github.com/holepunchto/bare#bareonunhandledrejection-reason-promise) for the underlying behavior. ## License diff --git a/android/CMakeLists.txt b/android/CMakeLists.txt deleted file mode 100644 index c726e45..0000000 --- a/android/CMakeLists.txt +++ /dev/null @@ -1,31 +0,0 @@ -add_library(bare_kit SHARED) - -set_target_properties( - bare_kit - PROPERTIES - C_STANDARD 11 - POSITION_INDEPENDENT_CODE ON - OUTPUT_NAME bare-kit -) - -target_sources( - bare_kit - PRIVATE - src/main/jni/IPC.c - src/main/jni/OnLoad.c - src/main/jni/Worklet.c -) - -target_link_libraries( - bare_kit - PRIVATE - android - PUBLIC - bare_worklet -) - -target_link_options( - bare_kit - PRIVATE - "-Wl,-z,global" -) diff --git a/android/build.gradle b/android/build.gradle deleted file mode 100644 index 7a779bd..0000000 --- a/android/build.gradle +++ /dev/null @@ -1,43 +0,0 @@ -plugins { - id "com.android.library" -} - -group = "to.holepunch" - -android { - namespace = "to.holepunch.bare.kit" - compileSdk 34 - ndkVersion = "28.2.13676358" - - defaultConfig { - minSdk 29 - targetSdk 34 - - externalNativeBuild { - cmake { - targets "bare_kit" - arguments "-DDRIVE_CORESTORE_DIR=build/_drive", "-DANDROID_STL=c++_shared" - } - } - - testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" - } - - externalNativeBuild { - cmake { - version = "4.0.0+" - path "../CMakeLists.txt" - } - } - - packagingOptions { - jniLibs { - excludes.add("**/libuv.so") - } - } -} - -dependencies { - androidTestImplementation "androidx.test:runner:+" - androidTestImplementation "androidx.test:rules:+" -} diff --git a/android/src/androidTest/java/to/holepunch/bare/kit/WorkletTest.java b/android/src/androidTest/java/to/holepunch/bare/kit/WorkletTest.java deleted file mode 100644 index 3df5af8..0000000 --- a/android/src/androidTest/java/to/holepunch/bare/kit/WorkletTest.java +++ /dev/null @@ -1,226 +0,0 @@ -package to.holepunch.bare.kit; - -import android.os.Handler; -import android.os.HandlerThread; -import android.os.Looper; -import android.util.Log; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class WorkletTest { - @Test - public void - IPC() throws InterruptedException { - HandlerThread thread = new HandlerThread("IPC"); - thread.start(); - - Handler handler = new Handler(thread.getLooper()); - - CountDownLatch latch = new CountDownLatch(1); - - handler.post(() -> { - Looper looper = Looper.myLooper(); - - Worklet worklet = new Worklet(null); - worklet.start("/app.js", "BareKit.IPC.on('data', (data) => BareKit.IPC.write(data)).write('Hello!')", StandardCharsets.UTF_8, null); - - IPC ipc = new IPC(worklet); - - ipc.read((data1, exception1) -> { - Log.v("BareKit", StandardCharsets.UTF_8.decode(data1).toString()); - - ipc.write(ByteBuffer.wrap("Hello back!".getBytes(StandardCharsets.UTF_8)), (exception2) -> { - ipc.read((data2, exception3) -> { - Log.v("BareKit", StandardCharsets.UTF_8.decode(data2).toString()); - - worklet.terminate(); - - latch.countDown(); - }); - }); - }); - }); - - latch.await(); - - thread.quit(); - } - - @Test - public void - IPCLargeWrite() throws InterruptedException { - HandlerThread thread = new HandlerThread("IPCLargeWrite"); - thread.start(); - - Handler handler = new Handler(thread.getLooper()); - - CountDownLatch latch = new CountDownLatch(1); - - handler.post(() -> { - Looper looper = Looper.myLooper(); - - Worklet worklet = new Worklet(null); - worklet.start("/app.js", "BareKit.IPC.on('data', (data) => BareKit.IPC.write(data))", StandardCharsets.UTF_8, null); - - IPC ipc = new IPC(worklet); - - ipc.write(ByteBuffer.allocateDirect(4 * 1024 * 1024), (exception) -> { - final AtomicInteger received = new AtomicInteger(0); - - ipc.readable(() -> { - ByteBuffer data = ipc.read(); - - if (received.addAndGet(data.limit()) == 4 * 1024 * 1024) { - worklet.terminate(); - - latch.countDown(); - } - }); - }); - }); - - latch.await(); - - thread.quit(); - } - - @Test - public void - Push() throws InterruptedException { - HandlerThread thread = new HandlerThread("Push"); - thread.start(); - - Handler handler = new Handler(thread.getLooper()); - - CountDownLatch latch = new CountDownLatch(1); - - handler.post(() -> { - Looper looper = Looper.myLooper(); - - Worklet worklet = new Worklet(null); - worklet.start( - "/app.js", - "BareKit.on('push', (json, reply) => {console.log(json.toString()); reply(null, 'Hello, world!')})", - StandardCharsets.UTF_8, - null - ); - - worklet.push("Push message", StandardCharsets.UTF_8, looper, (reply, exception) -> { - if (reply == null) return; - - Log.v("BareKit", reply); - - worklet.terminate(); - - latch.countDown(); - }); - }); - - latch.await(); - - thread.quit(); - } - - @Test - public void - IPCAfterTerminate() throws InterruptedException { - HandlerThread thread = new HandlerThread("IPCAfterTerminate"); - thread.start(); - - Handler handler = new Handler(thread.getLooper()); - - CountDownLatch latch = new CountDownLatch(1); - - handler.post(() -> { - Worklet worklet = new Worklet(null); - worklet.start("/app.js", "", StandardCharsets.UTF_8, null); - worklet.terminate(); - - try { - new IPC(worklet); - } catch (IllegalStateException exception) { - latch.countDown(); - } - }); - - latch.await(); - - thread.quit(); - } - - @Test - public void - IPCCloseOffLooper() throws InterruptedException { - HandlerThread thread = new HandlerThread("IPCCloseOffLooper"); - thread.start(); - - Handler handler = new Handler(thread.getLooper()); - - CountDownLatch opened = new CountDownLatch(1); - CountDownLatch closed = new CountDownLatch(1); - - final Worklet[] worklet = new Worklet[1]; - final IPC[] ipc = new IPC[1]; - - handler.post(() -> { - worklet[0] = new Worklet(null); - worklet[0].start("/app.js", "BareKit.IPC.on('data', () => {})", StandardCharsets.UTF_8, null); - - ipc[0] = new IPC(worklet[0]); - - ipc[0].readable(() -> {}); - - opened.countDown(); - }); - - opened.await(); - - ipc[0].close(); - ipc[0].close(); - - handler.post(() -> { - ByteBuffer data = ipc[0].read(); - - if (data != null && data.limit() == 0) closed.countDown(); - - worklet[0].terminate(); - }); - - closed.await(); - - thread.quit(); - } - - @Test - public void - PushAfterTerminate() throws InterruptedException { - HandlerThread thread = new HandlerThread("PushAfterTerminate"); - thread.start(); - - Handler handler = new Handler(thread.getLooper()); - - CountDownLatch latch = new CountDownLatch(1); - - handler.post(() -> { - Looper looper = Looper.myLooper(); - - Worklet worklet = new Worklet(null); - worklet.start("/app.js", "", StandardCharsets.UTF_8, null); - worklet.terminate(); - worklet.terminate(); - - worklet.push("Push message", StandardCharsets.UTF_8, looper, (reply, exception) -> { - if (exception != null) latch.countDown(); - }); - }); - - latch.await(); - - thread.quit(); - } -} diff --git a/android/src/main/AndroidManifest.xml b/android/src/main/AndroidManifest.xml deleted file mode 100644 index 94cbbcf..0000000 --- a/android/src/main/AndroidManifest.xml +++ /dev/null @@ -1 +0,0 @@ - diff --git a/android/src/main/java/to/holepunch/bare/kit/IPC.java b/android/src/main/java/to/holepunch/bare/kit/IPC.java deleted file mode 100644 index eda9afb..0000000 --- a/android/src/main/java/to/holepunch/bare/kit/IPC.java +++ /dev/null @@ -1,270 +0,0 @@ -package to.holepunch.bare.kit; - -import android.os.Handler; -import android.os.Looper; -import java.io.Closeable; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.util.concurrent.atomic.AtomicReference; -import to.holepunch.bare.kit.Worklet; - -public class IPC implements Closeable { - @FunctionalInterface - public interface PollCallback { - void - apply(); - } - - @FunctionalInterface - public interface ReadCallback { - void - apply(ByteBuffer data, Throwable exception); - } - - @FunctionalInterface - public interface WriteCallback { - void - apply(Throwable exception); - } - - ByteBuffer handle; - - // Held to keep the worklet reachable, as an IPC is meaningless without it. - private final Worklet worklet; - - private volatile PollCallback readable; - private volatile PollCallback writable; - - private final ByteBuffer buffer = ByteBuffer.allocateDirect(64 * 1024); - - // The looper of the opening thread, on which the callbacks run and the poll is - // changed. - private final Handler handler; - - /** - * Must be called on a thread with a looper, on which the callbacks then run. - * Throws if the worklet has terminated or already has an open IPC. - */ - public IPC(Worklet worklet) { - Looper looper = Looper.myLooper(); - - if (looper == null) throw new IllegalStateException("IPC must be opened on a looper thread"); - - this.worklet = worklet; - - handler = new Handler(looper); - - synchronized (worklet) { - if (worklet.handle == null) throw new IllegalStateException("Worklet terminated"); - - handle = init(worklet.handle); - } - - if (handle == null) throw new IllegalStateException("Could not open worklet IPC"); - } - - private native ByteBuffer - init(ByteBuffer handle); - - private native void - close(ByteBuffer handle); - - private native void - destroy(ByteBuffer handle); - - private native ByteBuffer - message(); - - private native int - read(ByteBuffer handle, ByteBuffer buffer); - - private native int - write(ByteBuffer handle, ByteBuffer data, int len); - - private native void - update(ByteBuffer handle, boolean readable, boolean writable); - - private void - update() { - if (handler.getLooper().isCurrentThread()) updateOnLooper(); - else handler.post(this::updateOnLooper); - } - - private synchronized void - updateOnLooper() { - if (handle == null) return; - - update(handle, readable != null, writable != null); - } - - // Called from native code. The callbacks are taken afresh for each event, as - // the previous one may have changed them. - private void - poll(boolean readable, boolean writable) { - if (readable) { - PollCallback callback = this.readable; - - if (callback != null) callback.apply(); - } - - if (writable) { - PollCallback callback = this.writable; - - if (callback != null) callback.apply(); - } - } - - public void - readable(PollCallback callback) { - readable = callback; - - update(); - } - - public void - writable(PollCallback callback) { - writable = callback; - - update(); - } - - /** - * Reads whatever is available without blocking. Returns null when nothing is - * ready yet, and an empty buffer at end-of-stream, once the worklet has - * closed its end or this IPC is closed. Wait for readable() before retrying - * a null. - */ - public synchronized ByteBuffer - read() { - if (handle == null) return ByteBuffer.allocateDirect(0); - - int len = read(handle, buffer); - - if (len < 0) return null; - - buffer.limit(len); - - ByteBuffer data = ByteBuffer.allocateDirect(len); - data.put(buffer); - data.flip(); - - buffer.clear(); - - return data; - } - - /** - * Reads once something is available, waiting for readable() as needed. - * Delivers null data at end-of-stream, once the worklet has closed its end or - * this IPC is closed. - */ - public void - read(ReadCallback callback) { - ByteBuffer data1 = read(); - - // A zero-length read is end-of-stream; signal it as null rather than an - // empty buffer so consumers can detect a closed IPC. - if (data1 != null) { - callback.apply(data1.limit() == 0 ? null : data1, null); - } else { - readable(() -> { - ByteBuffer data2 = read(); - - if (data2 != null) { - readable(null); - - callback.apply(data2.limit() == 0 ? null : data2, null); - } - }); - } - } - - /** - * Writes whatever fits without blocking, returning the number of bytes taken, - * or -1 once this IPC is closed or the worklet has exited. - */ - public synchronized int - write(ByteBuffer data) { - if (handle == null) return -1; - - ByteBuffer buffer; - - if (data.isDirect()) { - buffer = data; - } else { - buffer = ByteBuffer.allocateDirect(data.limit()); - buffer.put(data); - buffer.flip(); - } - - return write(handle, buffer, buffer.limit()); - } - - public void - write(ByteBuffer data, WriteCallback callback) { - ByteBuffer buffer; - - if (data.isDirect()) { - buffer = data.slice(); - } else { - buffer = ByteBuffer.allocateDirect(data.limit()); - buffer.put(data); - buffer.flip(); - } - - int written1 = write(buffer); - - if (written1 < 0) { - callback.apply(new IOException("IPC closed")); - } else if (written1 == buffer.limit()) { - callback.apply(null); - } else { - buffer.position(written1); - - final AtomicReference remaining = new AtomicReference<>(buffer.slice()); - - writable(() -> { - ByteBuffer slice = remaining.get(); - - int written2 = write(slice); - - if (written2 < 0) { - writable(null); - - callback.apply(new IOException("IPC closed")); - } else if (written2 == slice.limit()) { - writable(null); - - callback.apply(null); - } else { - slice.position(written2); - - remaining.set(slice.slice()); - } - }); - } - } - - /** - * Closing twice is a no-op. - */ - public void - close() { - ByteBuffer handle; - - synchronized (this) { - handle = this.handle; - - if (handle == null) return; - - this.handle = null; - - close(handle); - } - - // The poll belongs to the looper, so it is torn down there. - if (handler.getLooper().isCurrentThread()) destroy(handle); - else handler.post(() -> destroy(handle)); - } -} diff --git a/android/src/main/java/to/holepunch/bare/kit/Worklet.java b/android/src/main/java/to/holepunch/bare/kit/Worklet.java deleted file mode 100644 index af920e0..0000000 --- a/android/src/main/java/to/holepunch/bare/kit/Worklet.java +++ /dev/null @@ -1,308 +0,0 @@ -package to.holepunch.bare.kit; - -import android.os.Handler; -import android.os.Looper; -import java.io.Closeable; -import java.io.FileDescriptor; -import java.io.IOException; -import java.io.InputStream; -import java.lang.InterruptedException; -import java.nio.ByteBuffer; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; -import java.nio.charset.Charset; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - -public class Worklet implements Closeable { - static { - System.loadLibrary("bare-kit"); - } - - @FunctionalInterface - public interface PushCallback { - void - apply(T reply, Throwable exception); - } - - @FunctionalInterface - private interface NativePushCallback { - void - apply(ByteBuffer reply, String exception); - } - - public static class Options { - public int memoryLimit = 0; - public String assets = null; - - public Options - memoryLimit(int memoryLimit) { - this.memoryLimit = memoryLimit; - return this; - } - - public Options - assets(String assets) { - this.assets = assets; - return this; - } - } - - ByteBuffer handle; - - public Worklet(Options options) { - if (options == null) options = new Options(); - - handle = init(options.memoryLimit, options.assets); - } - - private native ByteBuffer - init(int memoryLimit, String assets); - - private native void - start(ByteBuffer handle, String filename, ByteBuffer source, int len, String[] arguments); - - private native void - suspend(ByteBuffer handle, int linger); - - private native void - resume(ByteBuffer handle); - - private native void - terminate(ByteBuffer handle); - - private native void - push(ByteBuffer handle, ByteBuffer payload, int len, NativePushCallback callback); - - private synchronized void - start(String filename, ByteBuffer source, int len, String[] arguments) { - if (handle == null) throw new IllegalStateException("Worklet terminated"); - - start(handle, filename, source, len, arguments); - } - - public void - start(String filename, String[] arguments) { - start(filename, null, 0, arguments); - } - - public void - start(String filename, ByteBuffer source, String[] arguments) { - if (source == null) { - start(filename, null, 0, arguments); - } else { - ByteBuffer buffer; - - if (source.isDirect()) { - buffer = source; - } else { - buffer = ByteBuffer.allocateDirect(source.limit()); - buffer.put(source); - buffer.flip(); - } - - start(filename, buffer, buffer.limit(), arguments); - } - } - - public void - start(String filename, String source, Charset charset, String[] arguments) { - start(filename, ByteBuffer.wrap(source.getBytes(charset)), arguments); - } - - public void - start(String filename, String source, String charset, String[] arguments) { - start(filename, source, Charset.forName(charset), arguments); - } - - public void - start(String filename, InputStream source, String[] arguments) throws IOException { - source.reset(); - - ByteBuffer buffer = ByteBuffer.allocateDirect(Math.max(4096, source.available())); - - ReadableByteChannel channel = Channels.newChannel(source); - - while (channel.read(buffer) != -1) { - if (buffer.hasRemaining()) continue; - - buffer.flip(); - - ByteBuffer resized = ByteBuffer.allocateDirect(buffer.capacity() * 2); - resized.put(buffer); - - buffer = resized; - } - - buffer.flip(); - channel.close(); - - start(filename, buffer, buffer.limit(), arguments); - } - - public void - suspend() { - suspend(-1); - } - - public synchronized void - suspend(int linger) { - if (handle == null) return; - - if (linger < 0) linger = 30000; - - suspend(handle, linger); - } - - public synchronized void - resume() { - if (handle == null) return; - - resume(handle); - } - - /** - * Terminating twice is a no-op, as are later calls to suspend() and resume(). - * Later pushes fail. - */ - public synchronized void - terminate() { - if (handle == null) return; - - terminate(handle); - - handle = null; - } - - private synchronized void - push(ByteBuffer payload, int len, NativePushCallback callback) { - if (handle == null) callback.apply(null, "Worklet is not running"); - else push(handle, payload, len, callback); - } - - private void - push(ByteBuffer payload, int len, Looper looper, PushCallback callback) { - Handler handler = Handler.createAsync(looper); - - push(payload, len, (reply, error) -> { - if (reply != null) { - ByteBuffer buffer = ByteBuffer.allocateDirect(reply.limit()); - buffer.put(reply); - buffer.flip(); - - handler.post(() -> callback.apply(buffer, null)); - } else if (error != null) { - Error exception = new Error(error); - - handler.post(() -> callback.apply(null, exception)); - } else { - handler.post(() -> callback.apply(null, null)); - } - }); - } - - private ByteBuffer - push(ByteBuffer payload, int len, long timeout, TimeUnit unit) throws InterruptedException { - final CountDownLatch latch = new CountDownLatch(1); - - final AtomicReference result = new AtomicReference<>(); - final AtomicReference exception = new AtomicReference<>(); - - push(payload, len, (reply, error) -> { - if (reply != null) { - ByteBuffer buffer = ByteBuffer.allocateDirect(reply.limit()); - buffer.put(reply); - buffer.flip(); - - result.set(buffer); - } else if (error != null) { - exception.set(new Error(error)); - } - - latch.countDown(); - }); - - latch.await(timeout, unit); - - if (exception.get() != null) throw exception.get(); - - return result.get(); - } - - public void - push(ByteBuffer payload, Looper looper, PushCallback callback) { - ByteBuffer buffer; - - if (payload.isDirect()) { - buffer = payload; - } else { - buffer = ByteBuffer.allocateDirect(payload.limit()); - buffer.put(payload); - buffer.flip(); - } - - push(buffer, buffer.limit(), looper, callback); - } - - public void - push(ByteBuffer payload, PushCallback callback) { - push(payload, Looper.myLooper(), callback); - } - - public ByteBuffer - push(ByteBuffer payload, long timeout, TimeUnit unit) throws InterruptedException { - ByteBuffer buffer; - - if (payload.isDirect()) { - buffer = payload; - } else { - buffer = ByteBuffer.allocateDirect(payload.limit()); - buffer.put(payload); - buffer.flip(); - } - - return push(buffer, buffer.limit(), timeout, unit); - } - - public void - push(String payload, Charset charset, Looper looper, PushCallback callback) { - push(ByteBuffer.wrap(payload.getBytes(charset)), (reply, error) -> { - callback.apply(reply == null ? null : charset.decode(reply).toString(), error); - }); - } - - public void - push(String payload, Charset charset, PushCallback callback) { - push(payload, charset, Looper.myLooper(), callback); - } - - public String - push(String payload, Charset charset, long timeout, TimeUnit unit) throws InterruptedException { - ByteBuffer reply = push(ByteBuffer.wrap(payload.getBytes(charset)), timeout, unit); - - if (reply == null) return null; - - return charset.decode(reply).toString(); - } - - public void - push(String payload, String charset, Looper looper, PushCallback callback) { - push(payload, Charset.forName(charset), callback); - } - - public void - push(String payload, String charset, PushCallback callback) { - push(payload, charset, Looper.myLooper(), callback); - } - - public String - push(String payload, String charset, long timeout, TimeUnit unit) throws InterruptedException { - return push(payload, Charset.forName(charset), timeout, unit); - } - - public void - close() { - terminate(); - } -} diff --git a/android/src/main/jni/IPC.c b/android/src/main/jni/IPC.c deleted file mode 100644 index fb1b318..0000000 --- a/android/src/main/jni/IPC.c +++ /dev/null @@ -1,132 +0,0 @@ -#include -#include -#include -#include - -#include - -#include "../../../../shared/ipc.h" -#include "../../../../shared/worklet.h" - -typedef struct { - bare_ipc_t ipc; - bare_ipc_poll_t poll; - - JNIEnv *env; - - jclass class; - jobject self; -} bare_ipc_context_t; - -JNIEXPORT jobject JNICALL -Java_to_holepunch_bare_kit_IPC_init(JNIEnv *env, jobject self, jobject handle) { - int err; - - bare_worklet_t *worklet = (bare_worklet_t *) (*env)->GetDirectBufferAddress(env, handle); - - bare_ipc_context_t *context = malloc(sizeof(bare_ipc_context_t)); - - context->env = env; - context->class = (*env)->NewGlobalRef(env, (*env)->GetObjectClass(env, self)); - context->self = (*env)->NewGlobalRef(env, self); - - err = bare_ipc_init(&context->ipc, worklet); - - if (err < 0) { - (*env)->DeleteGlobalRef(env, context->class); - (*env)->DeleteGlobalRef(env, context->self); - - free(context); - - return NULL; - } - - err = bare_ipc_poll_init(&context->poll, &context->ipc); - assert(err == 0); - - context->poll.data = (void *) context; - - return (*env)->NewDirectByteBuffer(env, (void *) context, sizeof(bare_ipc_context_t)); -} - -JNIEXPORT void JNICALL -Java_to_holepunch_bare_kit_IPC_close(JNIEnv *env, jobject self, jobject handle) { - bare_ipc_context_t *context = (bare_ipc_context_t *) (*env)->GetDirectBufferAddress(env, handle); - - bare_ipc_close(&context->ipc); -} - -JNIEXPORT void JNICALL -Java_to_holepunch_bare_kit_IPC_destroy(JNIEnv *env, jobject self, jobject handle) { - bare_ipc_context_t *context = (bare_ipc_context_t *) (*env)->GetDirectBufferAddress(env, handle); - - bare_ipc_poll_destroy(&context->poll); - bare_ipc_destroy(&context->ipc); - - (*env)->DeleteGlobalRef(env, context->class); - (*env)->DeleteGlobalRef(env, context->self); - - free(context); -} - -JNIEXPORT jint JNICALL -Java_to_holepunch_bare_kit_IPC_read(JNIEnv *env, jobject self, jobject handle, jobject jbuffer) { - bare_ipc_t *ipc = (bare_ipc_t *) (*env)->GetDirectBufferAddress(env, handle); - - void *data = (*env)->GetDirectBufferAddress(env, jbuffer); - size_t len = (size_t) (*env)->GetDirectBufferCapacity(env, jbuffer); - - int read = bare_ipc_read(ipc, data, len); - assert(read >= 0 || read == bare_ipc_would_block); - - return read; -} - -JNIEXPORT jint JNICALL -Java_to_holepunch_bare_kit_IPC_write(JNIEnv *env, jobject self, jobject handle, jobject jsource, jint jlen) { - int err; - - bare_ipc_t *ipc = (bare_ipc_t *) (*env)->GetDirectBufferAddress(env, handle); - - void *data = (*env)->GetDirectBufferAddress(env, jsource); - int len = (int) jlen; - err = bare_ipc_write(ipc, data, len); - - if (err == bare_ipc_would_block) return 0; - if (err < 0) return -1; - - return err; -} - -// A single call into Java, as the handlers it runs may close the IPC and free -// the context. -static void -bare_ipc__on_poll(bare_ipc_poll_t *poll, int events) { - bare_ipc_context_t *context = (bare_ipc_context_t *) poll->data; - - JNIEnv *env = context->env; - - jmethodID method = (*env)->GetMethodID(env, context->class, "poll", "(ZZ)V"); - - (*env)->CallVoidMethod(env, context->self, method, (jboolean) ((events & bare_ipc_readable) != 0), (jboolean) ((events & bare_ipc_writable) != 0)); -} - -JNIEXPORT void JNICALL -Java_to_holepunch_bare_kit_IPC_update(JNIEnv *env, jobject self, jobject handle, jboolean readable, jboolean writable) { - bare_ipc_context_t *context = (bare_ipc_context_t *) (*env)->GetDirectBufferAddress(env, handle); - - int events = 0; - - if (readable) events |= bare_ipc_readable; - if (writable) events |= bare_ipc_writable; - - int err; - - if (events) { - err = bare_ipc_poll_start(&context->poll, events, bare_ipc__on_poll); - assert(err == 0); - } else { - err = bare_ipc_poll_stop(&context->poll); - assert(err == 0); - } -} diff --git a/android/src/main/jni/OnLoad.c b/android/src/main/jni/OnLoad.c deleted file mode 100644 index 66b7381..0000000 --- a/android/src/main/jni/OnLoad.c +++ /dev/null @@ -1,10 +0,0 @@ -#include - -#include "../../../../shared/android/jvm.h" - -JNIEXPORT jint JNICALL -JNI_OnLoad(JavaVM *vm, void *reserved) { - bare_kit__jvm_set(vm); - - return JNI_VERSION_1_6; -} diff --git a/android/src/main/jni/Worklet.c b/android/src/main/jni/Worklet.c deleted file mode 100644 index 6dc81b9..0000000 --- a/android/src/main/jni/Worklet.c +++ /dev/null @@ -1,183 +0,0 @@ -#include -#include -#include - -#include "../../../../shared/worklet.h" - -typedef struct { - bare_worklet_push_t req; - - JavaVM *vm; - - jclass class; - jobject payload; - jobject callback; -} bare_worklet_push_context_t; - -JNIEXPORT jobject JNICALL -Java_to_holepunch_bare_kit_Worklet_init(JNIEnv *env, jobject self, jint jmemory_limit, jobject jassets) { - int err; - - bare_worklet_t *worklet = malloc(sizeof(bare_worklet_t)); - - bare_worklet_options_t options; - - options.memory_limit = (int) jmemory_limit; - - if ((*env)->IsSameObject(env, jassets, NULL)) { - options.assets = NULL; - } else { - options.assets = (*env)->GetStringUTFChars(env, jassets, NULL); - } - - err = bare_worklet_init(worklet, &options); - assert(err == 0); - - if (options.assets) { - (*env)->ReleaseStringUTFChars(env, jassets, options.assets); - } - - return (*env)->NewDirectByteBuffer(env, (void *) worklet, sizeof(bare_worklet_t)); -} - -JNIEXPORT void JNICALL -Java_to_holepunch_bare_kit_Worklet_start(JNIEnv *env, jobject self, jobject handle, jstring jfilename, jobject jsource, jint jlen, jobjectArray jarguments) { - int err; - - bare_worklet_t *worklet = (bare_worklet_t *) (*env)->GetDirectBufferAddress(env, handle); - - const char *filename = (*env)->GetStringUTFChars(env, jfilename, NULL); - - int argc = (*env)->IsSameObject(env, jarguments, NULL) ? 0 : (*env)->GetArrayLength(env, jarguments); - - const char **argv = calloc(argc, sizeof(char *)); - - for (int i = 0; i < argc; i++) { - jstring arg = (jstring) (*env)->GetObjectArrayElement(env, jarguments, i); - - argv[i] = (*env)->GetStringUTFChars(env, arg, NULL); - } - - if ((*env)->IsSameObject(env, jsource, NULL)) { - err = bare_worklet_start(worklet, filename, NULL, argc, argv); - assert(err == 0); - } else { - char *base = (*env)->GetDirectBufferAddress(env, jsource); - - int len = (int) jlen; - - uv_buf_t source = uv_buf_init(base, len); - - err = bare_worklet_start(worklet, filename, &source, argc, argv); - assert(err == 0); - } - - for (int i = 0; i < argc; i++) { - jstring arg = (jstring) (*env)->GetObjectArrayElement(env, jarguments, i); - - (*env)->ReleaseStringUTFChars(env, arg, argv[i]); - } - - (*env)->ReleaseStringUTFChars(env, jfilename, filename); -} - -JNIEXPORT void JNICALL -Java_to_holepunch_bare_kit_Worklet_suspend(JNIEnv *env, jobject self, jobject handle, jint jlinger) { - int err; - - int linger = (int) jlinger; - - bare_worklet_t *worklet = (bare_worklet_t *) (*env)->GetDirectBufferAddress(env, handle); - - err = bare_worklet_suspend(worklet, linger); - assert(err == 0); -} - -JNIEXPORT void JNICALL -Java_to_holepunch_bare_kit_Worklet_resume(JNIEnv *env, jobject self, jobject handle) { - int err; - - bare_worklet_t *worklet = (bare_worklet_t *) (*env)->GetDirectBufferAddress(env, handle); - - err = bare_worklet_resume(worklet); - assert(err == 0); -} - -JNIEXPORT void JNICALL -Java_to_holepunch_bare_kit_Worklet_terminate(JNIEnv *env, jobject self, jobject handle) { - int err; - - bare_worklet_t *worklet = (bare_worklet_t *) (*env)->GetDirectBufferAddress(env, handle); - - err = bare_worklet_terminate(worklet); - assert(err == 0); - - bare_worklet_destroy(worklet); - - free(worklet); -} - -static void -bare_worklet__on_push(bare_worklet_push_t *req, const char *error, const uv_buf_t *reply) { - int err; - - bare_worklet_push_context_t *context = (bare_worklet_push_context_t *) req->data; - - JNIEnv *env; - - err = (*context->vm)->GetEnv(context->vm, (void **) &env, JNI_VERSION_1_6); - assert(err == JNI_OK); - - jmethodID apply = (*env)->GetMethodID(env, context->class, "apply", "(Ljava/nio/ByteBuffer;Ljava/lang/String;)V"); - - jobject jerror; - - if (error) { - jerror = (*env)->NewStringUTF(env, error); - } else { - jerror = NULL; - } - - jobject jreply; - - if (reply) { - jreply = (*env)->NewDirectByteBuffer(env, (void *) reply->base, reply->len); - } else { - jreply = NULL; - } - - (*env)->CallVoidMethod(env, context->callback, apply, jreply, jerror); - - (*env)->DeleteGlobalRef(env, context->class); - (*env)->DeleteGlobalRef(env, context->payload); - (*env)->DeleteGlobalRef(env, context->callback); - - free(req); -} - -JNIEXPORT void JNICALL -Java_to_holepunch_bare_kit_Worklet_push(JNIEnv *env, jobject self, jobject handle, jobject jpayload, jint jlen, jobject jcallback) { - int err; - - bare_worklet_t *worklet = (bare_worklet_t *) (*env)->GetDirectBufferAddress(env, handle); - - char *base = (*env)->GetDirectBufferAddress(env, jpayload); - - int len = (int) jlen; - - uv_buf_t payload = uv_buf_init(base, len); - - bare_worklet_push_context_t *context = malloc(sizeof(bare_worklet_push_context_t)); - - context->req.data = (void *) context; - - (*env)->GetJavaVM(env, &context->vm); - - context->class = (*env)->NewGlobalRef(env, (*env)->GetObjectClass(env, jcallback)); - context->payload = (*env)->NewGlobalRef(env, jpayload); - context->callback = (*env)->NewGlobalRef(env, jcallback); - - err = bare_worklet_push(worklet, &context->req, &payload, bare_worklet__on_push); - - if (err < 0) bare_worklet__on_push(&context->req, "Worklet is not running", NULL); -} diff --git a/apple/BareKit/BareKit.h b/apple/BareKit/BareKit.h deleted file mode 100644 index f464b05..0000000 --- a/apple/BareKit/BareKit.h +++ /dev/null @@ -1,130 +0,0 @@ -#ifndef BARE_KIT_H -#define BARE_KIT_H - -#ifdef __OBJC__ - -#import - -@interface BareWorkletConfiguration : NSObject - -@property NSUInteger memoryLimit; -@property(nullable, copy) NSString *assets; - -+ (BareWorkletConfiguration *_Nullable)defaultWorkletConfiguration; - -@end - -@interface BareWorklet : NSObject - -+ (void)optimizeForMemory:(BOOL)enabled; - -- (_Nullable instancetype)initWithConfiguration:(BareWorkletConfiguration *_Nullable)options; - -/** - * Raises `NSInternalInconsistencyException` if the worklet has terminated or - * could not be started. - */ -- (void)start:(NSString *_Nonnull)filename - arguments:(NSArray *_Nullable)arguments; - -- (void)start:(NSString *_Nonnull)filename - source:(NSData *_Nullable)source - arguments:(NSArray *_Nullable)arguments; - -- (void)start:(NSString *_Nonnull)filename - source:(NSString *_Nonnull)source - encoding:(NSStringEncoding)encoding - arguments:(NSArray *_Nullable)arguments; - -- (void)start:(NSString *_Nonnull)name - ofType:(NSString *_Nonnull)type - arguments:(NSArray *_Nullable)arguments; - -- (void)start:(NSString *_Nonnull)name - ofType:(NSString *_Nonnull)type - inBundle:(NSBundle *_Nonnull)bundle - arguments:(NSArray *_Nullable)arguments; - -- (void)start:(NSString *_Nonnull)name - ofType:(NSString *_Nonnull)type - inDirectory:(NSString *_Nonnull)subpath - arguments:(NSArray *_Nullable)arguments; - -- (void)start:(NSString *_Nonnull)name - ofType:(NSString *_Nonnull)type - inDirectory:(NSString *_Nonnull)subpath - inBundle:(NSBundle *_Nonnull)bundle - arguments:(NSArray *_Nullable)arguments; - -- (void)suspend; -- (void)suspendWithLinger:(int)linger; -- (void)resume; -- (void)terminate; - -- (void)push:(NSData *_Nonnull)payload - queue:(NSOperationQueue *_Nonnull)queue - completion:(void (^_Nonnull)(NSData *_Nullable reply, NSError *_Nullable error))completion; - -- (void)push:(NSData *_Nonnull)payload - completion:(void (^_Nonnull)(NSData *_Nullable reply, NSError *_Nullable error))completion; - -- (void)push:(NSString *_Nonnull)payload - encoding:(NSStringEncoding)encoding - queue:(NSOperationQueue *_Nonnull)queue - completion:(void (^_Nonnull)(NSString *_Nullable reply, NSError *_Nullable error))completion; - -- (void)push:(NSString *_Nonnull)payload - encoding:(NSStringEncoding)encoding - completion:(void (^_Nonnull)(NSString *_Nullable reply, NSError *_Nullable error))completion; - -@end - -@interface BareIPC : NSObject - -@property(nonatomic, copy, nullable) void (^readable)(BareIPC *_Nonnull); -@property(nonatomic, copy, nullable) void (^writable)(BareIPC *_Nonnull); - -/** - * Returns `nil` if the worklet has terminated or already has an open ipc. - */ -- (_Nullable instancetype)initWithWorklet:(BareWorklet *_Nonnull)worklet; - -/** - * Reads whatever is available without blocking. Returns `nil` when nothing is - * ready yet, and empty data at end-of-stream, once the worklet has closed its - * end or this ipc is closed. Wait for `readable` before retrying a `nil`. - */ -- (NSData *_Nullable)read; - -/** - * Reads once something is available, waiting for `readable` as needed. Delivers - * `nil` data at end-of-stream, once the worklet has closed its end or this ipc - * is closed. A pending read keeps this ipc alive until it completes, which - * closing does. - */ -- (void)read:(void (^_Nonnull)(NSData *_Nullable data, NSError *_Nullable error))completion; - -/** - * Writes whatever fits without blocking, returning the number of bytes taken, - * or -1 once this ipc is closed or the worklet has exited. - */ -- (NSInteger)write:(NSData *_Nonnull)data; - -/** - * Writes all of the data, waiting for `writable` as needed. A pending write - * keeps this ipc alive until it completes, which closing does. - */ -- (void)write:(NSData *_Nonnull)data - completion:(void (^_Nonnull)(NSError *_Nullable error))completion; - -/** - * Closes this ipc, after which reads return end-of-stream and writes fail. - * Closing twice is a no-op. - */ -- (void)close; - -@end - -#endif - -#endif // BARE_KIT_H diff --git a/apple/BareKit/BareKit.m b/apple/BareKit/BareKit.m deleted file mode 100644 index 7718186..0000000 --- a/apple/BareKit/BareKit.m +++ /dev/null @@ -1,537 +0,0 @@ -#import -#import - -#import -#import -#import -#import - -#import "BareKit.h" - -#import "../../shared/ipc.h" -#import "../../shared/worklet.h" - -typedef void (^BareWorkletPushHandler)(NSData *_Nullable reply, NSError *_Nullable error); - -@interface BareWorkletPushContext : NSObject - -@property(nonatomic, copy) BareWorkletPushHandler handler; -@property(nonatomic, strong) NSData *payload; -@property(nonatomic, strong) NSOperationQueue *queue; - -- (_Nullable instancetype)initWithHandler:(BareWorkletPushHandler)handler - payload:(NSData *)payload - queue:(NSOperationQueue *)queue; - -@end - -@implementation BareWorkletPushContext { -@public - bare_worklet_push_t _req; -} - -- (_Nullable instancetype)initWithHandler:(BareWorkletPushHandler)handler - payload:(NSData *)payload - queue:(NSOperationQueue *)queue { - self = [super init]; - - if (self) { - _handler = [handler copy]; - _payload = [payload retain]; - _queue = [queue retain]; - _req.data = (__bridge void *) self; - } - - return self; -} - -- (void)dealloc { - [_handler release]; - [_payload release]; - [_queue release]; - - [super dealloc]; -} - -@end - -static NSError * -bare_kit__error(NSString *message) { - return [NSError - errorWithDomain:@"to.holepunch.bare.kit" - code:-1 - userInfo:@{NSLocalizedDescriptionKey : message}]; -} - -static void -bare_worklet__on_push(bare_worklet_push_t *req, const char *err, const uv_buf_t *reply) { - @autoreleasepool { - // Owned by the request since the push and released here rather than by the - // operation below, as a queue releases its finished operations at no set - // time. - BareWorkletPushContext *context = (__bridge BareWorkletPushContext *) req->data; - - NSError *error; - - if (err) { - error = bare_kit__error([NSString stringWithUTF8String:err]); - - } else { - error = nil; - } - - NSData *data; - - if (reply) { - data = [NSData dataWithBytes:reply->base length:reply->len]; - } else { - data = nil; - } - - BareWorkletPushHandler handler = context.handler; - - [context.queue addOperationWithBlock:^{ - handler(data, error); - }]; - - [context release]; - } -} - -@implementation BareWorkletConfiguration - -+ (BareWorkletConfiguration *_Nullable)defaultWorkletConfiguration { - return [[BareWorkletConfiguration alloc] init]; -} - -- (_Nullable instancetype)init { - self = [super init]; - - if (self) { - _memoryLimit = 0; - _assets = nil; - } - - return self; -} - -@end - -@implementation BareWorklet { -@public - bare_worklet_t _worklet; - - bool _terminated; -} - -+ (void)optimizeForMemory:(BOOL)enabled { - int err; - err = bare_worklet_optimize_for_memory(enabled); - assert(err == 0); -} - -- (_Nullable instancetype)initWithConfiguration:(BareWorkletConfiguration *_Nullable)options { - self = [super init]; - - if (self) { - bare_worklet_options_t _options; - - if (options) { - _options.memory_limit = options.memoryLimit; - _options.assets = options.assets == nil ? nil : [options.assets UTF8String]; - } else { - _options.memory_limit = 0; - _options.assets = nil; - } - - int err; - err = bare_worklet_init(&_worklet, &_options); - assert(err == 0); - - _worklet.data = (__bridge void *) self; - } - - return self; -} - -- (void)start:(NSString *_Nonnull)filename - arguments:(NSArray *_Nullable)arguments { - [self start:filename source:nil arguments:arguments]; -} - -- (void)start:(NSString *_Nonnull)filename - source:(NSData *_Nullable)source - arguments:(NSArray *_Nullable)arguments { - const char *_filename = [filename cStringUsingEncoding:NSUTF8StringEncoding]; - - int argc = arguments == nil ? 0 : [arguments count]; - - const char **argv = calloc(argc, sizeof(char *)); - - for (int i = 0; i < argc; i++) { - argv[i] = [arguments[i] UTF8String]; - } - - uv_buf_t _source; - - if (source) _source = uv_buf_init((char *) source.bytes, source.length); - - int err; - - @synchronized(self) { - err = _terminated ? -1 : bare_worklet_start(&_worklet, _filename, source ? &_source : NULL, argc, argv); - } - - free(argv); - - if (err < 0) [NSException raise:NSInternalInconsistencyException format:@"Worklet could not be started"]; -} - -- (void)start:(NSString *_Nonnull)filename - source:(NSString *_Nonnull)source - encoding:(NSStringEncoding)encoding - arguments:(NSArray *_Nullable)arguments { - [self start:filename source:[source dataUsingEncoding:encoding] arguments:arguments]; -} -- (void)start:(NSString *_Nonnull)name - ofType:(NSString *_Nonnull)type - arguments:(NSArray *_Nullable)arguments { - [self start:name ofType:type inBundle:[NSBundle mainBundle] arguments:arguments]; -} - -- (void)start:(NSString *_Nonnull)name - ofType:(NSString *_Nonnull)type - inBundle:(NSBundle *_Nonnull)bundle - arguments:(NSArray *_Nullable)arguments { - [self start:[bundle pathForResource:name ofType:type] arguments:arguments]; -} - -- (void)start:(NSString *_Nonnull)name - ofType:(NSString *_Nonnull)type - inDirectory:(NSString *_Nonnull)subpath - arguments:(NSArray *_Nullable)arguments { - [self start:name ofType:type inDirectory:subpath inBundle:[NSBundle mainBundle] arguments:arguments]; -} - -- (void)start:(NSString *_Nonnull)name - ofType:(NSString *_Nonnull)type - inDirectory:(NSString *_Nonnull)subpath - inBundle:(NSBundle *_Nonnull)bundle - arguments:(NSArray *_Nullable)arguments { - [self start:[bundle pathForResource:name ofType:type inDirectory:subpath] arguments:arguments]; -} - -- (void)suspend { - [self suspendWithLinger:-1]; -} - -// The lifecycle methods are serialized, as terminating destroys the worklet the -// others use. -- (void)suspendWithLinger:(int)linger { - @synchronized(self) { - if (_terminated) return; - - int err; - err = bare_worklet_suspend(&_worklet, linger); - assert(err == 0); - } -} - -- (void)resume { - @synchronized(self) { - if (_terminated) return; - - int err; - err = bare_worklet_resume(&_worklet); - assert(err == 0); - } -} - -- (void)terminate { - @synchronized(self) { - if (_terminated) return; - - _terminated = true; - - int err; - err = bare_worklet_terminate(&_worklet); - assert(err == 0); - - bare_worklet_destroy(&_worklet); - } -} - -- (void)dealloc { - [self terminate]; - - [super dealloc]; -} - -- (void)push:(NSData *_Nonnull)payload - queue:(NSOperationQueue *_Nonnull)queue - completion:(void (^_Nonnull)(NSData *_Nullable reply, NSError *_Nullable error))completion { - BareWorkletPushContext *context = [[BareWorkletPushContext alloc] - initWithHandler:completion - payload:payload - queue:queue]; - - uv_buf_t buf = uv_buf_init((char *) payload.bytes, payload.length); - - int err; - - @synchronized(self) { - err = _terminated ? -1 : bare_worklet_push(&_worklet, &context->_req, &buf, bare_worklet__on_push); - } - - if (err < 0) bare_worklet__on_push(&context->_req, "Worklet is not running", NULL); -} - -- (void)push:(NSData *_Nonnull)payload - completion:(void (^_Nonnull)(NSData *_Nullable reply, NSError *_Nullable error))completion { - [self push:payload queue:[NSOperationQueue mainQueue] completion:completion]; -} - -- (void)push:(NSString *_Nonnull)payload - encoding:(NSStringEncoding)encoding - queue:(NSOperationQueue *_Nonnull)queue - completion:(void (^_Nonnull)(NSString *_Nullable reply, NSError *_Nullable error))completion { - [self push:[payload dataUsingEncoding:encoding] - queue:queue - completion:^(NSData *reply, NSError *error) { - completion(reply == nil ? nil : [[NSString alloc] initWithData:reply encoding:encoding], error); - }]; -} - -- (void)push:(NSString *_Nonnull)payload - encoding:(NSStringEncoding)encoding - completion:(void (^_Nonnull)(NSString *_Nullable reply, NSError *_Nullable error))completion { - [self push:payload encoding:encoding queue:[NSOperationQueue mainQueue] completion:completion]; -} - -@end - -@interface BareIPC () - -- (void)poll:(int)events; - -@end - -static void -bare_ipc__on_poll(bare_ipc_poll_t *poll, int events) { - @autoreleasepool { - // Nil once the ipc has begun deallocating. Otherwise held until the pool - // drains, so dealloc never runs, or waits, while a handler does. - BareIPC *ipc = objc_loadWeak((id *) poll->data); - - [ipc poll:events]; - } -} - -@implementation BareIPC { - // Retained, as an IPC is meaningless without its worklet. Nil if init failed, - // in which case there is nothing to destroy. - BareWorklet *_worklet; - - bare_ipc_t _ipc; - bare_ipc_poll_t _poll; - - id _weak; -} - -- (_Nullable instancetype)initWithWorklet:(BareWorklet *_Nonnull)worklet { - self = [super init]; - - if (self) { - int err; - - @synchronized(worklet) { - err = worklet->_terminated ? -1 : bare_ipc_init(&_ipc, &worklet->_worklet); - } - - if (err < 0) { - [self release]; - - return nil; - } - - _worklet = [worklet retain]; - - err = bare_ipc_poll_init(&_poll, &_ipc); - assert(err == 0); - - objc_storeWeak(&_weak, self); - - _poll.data = &_weak; - } - - return self; -} - -// The handlers run on the poll queue while the setters may run anywhere, so -// they are swapped and taken under a lock, and only released outside it. -- (void)setReadable:(void (^)(BareIPC *_Nonnull))readable { - readable = [readable copy]; - - @synchronized(self) { - void (^previous)(BareIPC *) = _readable; - _readable = readable; - readable = previous; - } - - [readable release]; - - [self update]; -} - -- (void)setWritable:(void (^)(BareIPC *_Nonnull))writable { - writable = [writable copy]; - - @synchronized(self) { - void (^previous)(BareIPC *) = _writable; - _writable = writable; - writable = previous; - } - - [writable release]; - - [self update]; -} - -// Under the lock throughout, so that concurrent updates apply in order. -- (void)update { - @synchronized(self) { - int events = 0; - - if (_readable) events |= bare_ipc_readable; - if (_writable) events |= bare_ipc_writable; - - int err; - - if (events) { - err = bare_ipc_poll_start(&_poll, events, bare_ipc__on_poll); - assert(err == 0); - } else { - err = bare_ipc_poll_stop(&_poll); - assert(err == 0); - } - } -} - -- (void)poll:(int)events { - if (events & bare_ipc_readable) [self invoke:bare_ipc_readable]; - if (events & bare_ipc_writable) [self invoke:bare_ipc_writable]; -} - -// Taken afresh for each event, as the previous handler may have changed it. -- (void)invoke:(int)event { - void (^handler)(BareIPC *); - - @synchronized(self) { - handler = [(event == bare_ipc_readable ? _readable : _writable) retain]; - } - - if (handler) handler(self); - - [handler release]; -} - -- (NSData *_Nullable)read { - NSMutableData *data = [NSMutableData dataWithLength:BARE_IPC_READ_BUFFER_SIZE]; - - int len = bare_ipc_read(&_ipc, data.mutableBytes, data.length); - assert(len >= 0 || len == bare_ipc_would_block); - - if (len == bare_ipc_would_block) { - return nil; - } - - data.length = len; - - return data; -} - -- (void)read:(void (^_Nonnull)(NSData *_Nullable data, NSError *_Nullable error))completion { - NSData *data = [self read]; - - if (data == nil) { - self.readable = ^(BareIPC *ipc) { - self.readable = nil; - - [self read:completion]; - }; - - return; - } - - // A successful read of zero bytes is end-of-stream; signal it as nil rather - // than an empty buffer so consumers can detect a closed IPC. - completion(data.length == 0 ? nil : data, nil); -} - -- (NSInteger)write:(NSData *_Nonnull)data { - int err; - err = bare_ipc_write(&_ipc, data.bytes, data.length); - - if (err == bare_ipc_would_block) return 0; - if (err < 0) return -1; - - return err; -} - -- (void)write:(NSData *_Nonnull)data - completion:(void (^_Nonnull)(NSError *_Nullable error))completion { - NSInteger written = [self write:data]; - - if (written < 0) { - completion(bare_kit__error(@"IPC closed")); - } else if (written == data.length) { - completion(nil); - } else { - data = [data subdataWithRange:NSMakeRange(written, data.length - written)]; - - [data retain]; - - __block NSData *remaining = data; - - self.writable = ^(BareIPC *ipc) { - NSInteger written = [self write:remaining]; - - if (written < 0 || written == remaining.length) { - [remaining release]; - - self.writable = nil; - - completion(written < 0 ? bare_kit__error(@"IPC closed") : nil); - } else { - NSData *data = [remaining subdataWithRange:NSMakeRange(written, remaining.length - written)]; - - [data retain]; - [remaining release]; - - remaining = data; - } - }; - } -} - -- (void)close { - bare_ipc_close(&_ipc); -} - -- (void)dealloc { - if (_worklet) { - bare_ipc_poll_destroy(&_poll); - bare_ipc_destroy(&_ipc); - - [_worklet release]; - } - - [_readable release]; - [_writable release]; - - objc_storeWeak(&_weak, nil); - - [super dealloc]; -} - -@end diff --git a/apple/BareKit/iOS.plist b/apple/BareKit/iOS.plist deleted file mode 100644 index 131486b..0000000 --- a/apple/BareKit/iOS.plist +++ /dev/null @@ -1,30 +0,0 @@ - - - - - CFBundleDevelopmentRegion - English - CFBundleExecutable - ${MACOSX_FRAMEWORK_NAME} - CFBundleIconFile - ${MACOSX_FRAMEWORK_ICON_FILE} - CFBundleIdentifier - ${MACOSX_FRAMEWORK_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${MACOSX_FRAMEWORK_BUNDLE_NAME} - CFBundlePackageType - FMWK - CFBundleSignature - ???? - CFBundleVersion - ${MACOSX_FRAMEWORK_BUNDLE_VERSION} - CFBundleShortVersionString - ${MACOSX_FRAMEWORK_SHORT_VERSION_STRING} - CSResourcesFileMapped - - MinimumOSVersion - ${CMAKE_OSX_DEPLOYMENT_TARGET} - - diff --git a/apple/BareKit/macOS.plist b/apple/BareKit/macOS.plist deleted file mode 100644 index 585e703..0000000 --- a/apple/BareKit/macOS.plist +++ /dev/null @@ -1,30 +0,0 @@ - - - - - CFBundleDevelopmentRegion - English - CFBundleExecutable - ${MACOSX_FRAMEWORK_NAME} - CFBundleIconFile - ${MACOSX_FRAMEWORK_ICON_FILE} - CFBundleIdentifier - ${MACOSX_FRAMEWORK_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${MACOSX_FRAMEWORK_BUNDLE_NAME} - CFBundlePackageType - FMWK - CFBundleSignature - ???? - CFBundleVersion - ${MACOSX_FRAMEWORK_BUNDLE_VERSION} - CFBundleShortVersionString - ${MACOSX_FRAMEWORK_SHORT_VERSION_STRING} - CSResourcesFileMapped - - LSMinimumSystemVersion - ${CMAKE_OSX_DEPLOYMENT_TARGET} - - diff --git a/apple/CMakeLists.txt b/apple/CMakeLists.txt deleted file mode 100644 index 8ab36ea..0000000 --- a/apple/CMakeLists.txt +++ /dev/null @@ -1,59 +0,0 @@ -add_library(bare_kit SHARED) - -set_target_properties( - bare_kit - PROPERTIES - OBJC_STANDARD 11 - FRAMEWORK TRUE - OUTPUT_NAME BareKit - PUBLIC_HEADER BareKit/BareKit.h - - MACOSX_FRAMEWORK_BUNDLE_NAME "BareKit" - MACOSX_FRAMEWORK_IDENTIFIER "to.holepunch.bare.kit" - MACOSX_FRAMEWORK_BUNDLE_VERSION ${PROJECT_VERSION} - MACOSX_FRAMEWORK_SHORT_VERSION_STRING ${PROJECT_VERSION} -) - -if(IOS) - set_target_properties( - bare_kit - PROPERTIES - MACOSX_FRAMEWORK_INFO_PLIST "${CMAKE_CURRENT_LIST_DIR}/BareKit/iOS.plist" - ) -else() - set_target_properties( - bare_kit - PROPERTIES - MACOSX_FRAMEWORK_INFO_PLIST "${CMAKE_CURRENT_LIST_DIR}/BareKit/macOS.plist" - ) -endif() - -target_sources( - bare_kit - PUBLIC - BareKit/BareKit.h - PRIVATE - BareKit/BareKit.m -) - -target_include_directories( - bare_kit - PUBLIC - . -) - -target_link_libraries( - bare_kit - PUBLIC - "-framework Foundation" - PUBLIC - bare_worklet -) - -if(IOS) - target_link_libraries( - bare_kit - PUBLIC - "-framework UIKit" - ) -endif() diff --git a/build.gradle b/build.gradle deleted file mode 100644 index 3344512..0000000 --- a/build.gradle +++ /dev/null @@ -1,3 +0,0 @@ -plugins { - id "com.android.library" version "8.12.0" apply false -} diff --git a/gradle.properties b/gradle.properties deleted file mode 100644 index d7ba8f4..0000000 --- a/gradle.properties +++ /dev/null @@ -1 +0,0 @@ -android.useAndroidX = true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index e644113..0000000 Binary files a/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index d4081da..0000000 --- a/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,7 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew deleted file mode 100755 index b740cf1..0000000 --- a/gradlew +++ /dev/null @@ -1,249 +0,0 @@ -#!/bin/sh - -# -# Copyright © 2015-2021 the original authors. -# -# 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 -# -# https://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. -# - -############################################################################## -# -# Gradle start up script for POSIX generated by Gradle. -# -# Important for running: -# -# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is -# noncompliant, but you have some other compliant shell such as ksh or -# bash, then to run this script, type that shell name before the whole -# command line, like: -# -# ksh Gradle -# -# Busybox and similar reduced shells will NOT work, because this script -# requires all of these POSIX shell features: -# * functions; -# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», -# «${var#prefix}», «${var%suffix}», and «$( cmd )»; -# * compound commands having a testable exit status, especially «case»; -# * various built-in commands including «command», «set», and «ulimit». -# -# Important for patching: -# -# (2) This script targets any POSIX shell, so it avoids extensions provided -# by Bash, Ksh, etc; in particular arrays are avoided. -# -# The "traditional" practice of packing multiple parameters into a -# space-separated string is a well documented source of bugs and security -# problems, so this is (mostly) avoided, by progressively accumulating -# options in "$@", and eventually passing that to Java. -# -# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, -# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; -# see the in-line comments for details. -# -# There are tweaks for specific operating systems such as AIX, CygWin, -# Darwin, MinGW, and NonStop. -# -# (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt -# within the Gradle project. -# -# You can find Gradle at https://github.com/gradle/gradle/. -# -############################################################################## - -# Attempt to set APP_HOME - -# Resolve links: $0 may be a link -app_path=$0 - -# Need this for daisy-chained symlinks. -while - APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path - [ -h "$app_path" ] -do - ls=$( ls -ld "$app_path" ) - link=${ls#*' -> '} - case $link in #( - /*) app_path=$link ;; #( - *) app_path=$APP_HOME$link ;; - esac -done - -# This is normally unused -# shellcheck disable=SC2034 -APP_BASE_NAME=${0##*/} -# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD=maximum - -warn () { - echo "$*" -} >&2 - -die () { - echo - echo "$*" - echo - exit 1 -} >&2 - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "$( uname )" in #( - CYGWIN* ) cygwin=true ;; #( - Darwin* ) darwin=true ;; #( - MSYS* | MINGW* ) msys=true ;; #( - NONSTOP* ) nonstop=true ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD=$JAVA_HOME/jre/sh/java - else - JAVACMD=$JAVA_HOME/bin/java - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD=java - if ! command -v java >/dev/null 2>&1 - then - die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -fi - -# Increase the maximum file descriptors if we can. -if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then - case $MAX_FD in #( - max*) - # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC2039,SC3045 - MAX_FD=$( ulimit -H -n ) || - warn "Could not query maximum file descriptor limit" - esac - case $MAX_FD in #( - '' | soft) :;; #( - *) - # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC2039,SC3045 - ulimit -n "$MAX_FD" || - warn "Could not set maximum file descriptor limit to $MAX_FD" - esac -fi - -# Collect all arguments for the java command, stacking in reverse order: -# * args from the command line -# * the main class name -# * -classpath -# * -D...appname settings -# * --module-path (only if needed) -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. - -# For Cygwin or MSYS, switch paths to Windows format before running java -if "$cygwin" || "$msys" ; then - APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - - JAVACMD=$( cygpath --unix "$JAVACMD" ) - - # Now convert the arguments - kludge to limit ourselves to /bin/sh - for arg do - if - case $arg in #( - -*) false ;; # don't mess with options #( - /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath - [ -e "$t" ] ;; #( - *) false ;; - esac - then - arg=$( cygpath --path --ignore --mixed "$arg" ) - fi - # Roll the args list around exactly as many times as the number of - # args, so each arg winds up back in the position where it started, but - # possibly modified. - # - # NB: a `for` loop captures its iteration list before it begins, so - # changing the positional parameters here affects neither the number of - # iterations, nor the values presented in `arg`. - shift # remove old arg - set -- "$@" "$arg" # push replacement arg - done -fi - - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Collect all arguments for the java command: -# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, -# and any embedded shellness will be escaped. -# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be -# treated as '${Hostname}' itself on the command line. - -set -- \ - "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ - "$@" - -# Stop when "xargs" is not available. -if ! command -v xargs >/dev/null 2>&1 -then - die "xargs is not available" -fi - -# Use "xargs" to parse quoted args. -# -# With -n1 it outputs one arg per line, with the quotes and backslashes removed. -# -# In Bash we could simply go: -# -# readarray ARGS < <( xargs -n1 <<<"$var" ) && -# set -- "${ARGS[@]}" "$@" -# -# but POSIX shell has neither arrays nor command substitution, so instead we -# post-process each arg (as a line of input to sed) to backslash-escape any -# character that might be a shell metacharacter, then use eval to reverse -# that process (while maintaining the separation between arguments), and wrap -# the whole thing up as a single "set" statement. -# -# This will of course break if any of these variables contains a newline or -# an unmatched quote. -# - -eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | - xargs -n1 | - sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | - tr '\n' ' ' - )" '"$@"' - -exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat deleted file mode 100644 index 7101f8e..0000000 --- a/gradlew.bat +++ /dev/null @@ -1,92 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%"=="" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -@rem This is normally unused -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if %ERRORLEVEL% equ 0 goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/include/bare-kit.h b/include/bare-kit.h new file mode 100644 index 0000000..33b9ec4 --- /dev/null +++ b/include/bare-kit.h @@ -0,0 +1,321 @@ +#ifndef BARE_KIT_H +#define BARE_KIT_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +typedef struct bare_worklet_s bare_worklet_t; +typedef struct bare_worklet_options_s bare_worklet_options_t; +typedef struct bare_ipc_s bare_ipc_t; +typedef struct bare_ipc_poll_s bare_ipc_poll_t; + +typedef void (*bare_worklet_suspend_cb)(int linger, void *data); +typedef void (*bare_worklet_wakeup_cb)(int deadline, void *data); +typedef void (*bare_worklet_idle_cb)(void *data); +typedef void (*bare_worklet_resume_cb)(void *data); +typedef void (*bare_worklet_exit_cb)(int exit_code, void *data); +typedef void (*bare_ipc_poll_cb)(bare_ipc_poll_t *, int events); + +#define BARE_IPC_READ_BUFFER_SIZE (64 * 1024) + +enum { + bare_ipc_readable = 0x1, + bare_ipc_writable = 0x2, +}; + +enum { + bare_ipc_would_block = -1, + bare_ipc_error = -2, +}; + +/** @version 0 */ +struct bare_worklet_options_s { + int version; + + /** + * The memory limit of each JavaScript heap. By default, the limit will be + * inferred based on the amount of physical memory of the device. + * + * Note that the limit applies individually to each thread, including the + * main thread. + * + * @since 0 + */ + size_t memory_limit; + + /** + * Options that are specific to a platform. Only the member of the platform + * that the worklet runs on is read. The size of the union is fixed by + * `reserved`, so that fields added to the end of the options keep their + * offsets as the members of the union grow. + * + * @since 0 + */ + union { + /** + * Options that apply on Android. + */ + struct { + /** + * The Java virtual machine, as a `JavaVM *`, which is published to the + * addons of the worklet under `bare.android.jvm.v1`. By default, the + * virtual machine that loaded Bare Kit through `JNI_OnLoad()` is used, so + * it must be given if Bare Kit is loaded by other means. There is only + * one per process. + */ + void *jvm; + + /** + * The application context, as a JNI reference to an + * `android.content.Context`, which is published to the addons of the + * worklet under `bare.android.context.v1`. The worklet takes a global + * reference of its own, so the reference need only be valid for the call. + */ + void *context; + } android; + + void *reserved[8]; + } platform; +}; + +/** + * Enable trade-off of performance for memory. Must be configured before + * starting the first worklet. + */ +int +bare_worklet_optimize_for_memory(bool enabled); + +/** + * Tear down the state shared by the worklets of the process. Every worklet must + * have been terminated or destroyed first, and those still tearing down are + * waited for. Must be called at most once, after which starting a worklet + * fails. A host that runs worklets for as long as it lives need not call it. + */ +int +bare_worklet_teardown(void); + +/** + * Create a worklet. The options are copied and may be `NULL`. On Android, the + * calling thread must be attached to the JVM if an application context is + * given. + */ +int +bare_worklet_create(const bare_worklet_options_t *options, bare_worklet_t **result); + +/** + * Terminate the worklet if it is still running and hand it over to tear itself + * down, without blocking. The worklet must not be used afterwards, but its ipc + * may be destroyed before or after it. + */ +void +bare_worklet_destroy(bare_worklet_t *worklet); + +// Lifecycle callbacks, called on the worklet thread. They must be configured +// before starting the worklet. + +/** + * Called when the worklet suspends, with the number of milliseconds that it + * lingers for before going idle. + */ +int +bare_worklet_on_suspend(bare_worklet_t *worklet, bare_worklet_suspend_cb cb, void *data); + +/** + * Called when a suspended worklet wakes up, with the number of milliseconds + * that it has to perform background work before going idle again. + */ +int +bare_worklet_on_wakeup(bare_worklet_t *worklet, bare_worklet_wakeup_cb cb, void *data); + +/** + * Called when a suspended worklet goes idle, after which it does no work until + * it is resumed or woken up. + */ +int +bare_worklet_on_idle(bare_worklet_t *worklet, bare_worklet_idle_cb cb, void *data); + +/** + * Called when a suspended worklet resumes. + */ +int +bare_worklet_on_resume(bare_worklet_t *worklet, bare_worklet_resume_cb cb, void *data); + +/** + * Called exactly once on the worklet thread with the exit code of the worklet + * once it has torn down, whether it exited on its own, was terminated, or was + * destroyed, so `data` must be kept until then. An ipc of the worklet has + * reached end-of-stream by then. + */ +int +bare_worklet_on_exit(bare_worklet_t *worklet, bare_worklet_exit_cb cb, void *data); + +/** + * Get the data that was associated with the worklet by + * `bare_worklet_set_data()`. + */ +void * +bare_worklet_get_data(bare_worklet_t *worklet); + +/** + * Associate `data` with the worklet, for the host to retrieve with + * `bare_worklet_get_data()`. The worklet does not use it. + */ +void +bare_worklet_set_data(bare_worklet_t *worklet, void *data); + +/** + * Start the worklet on a thread of its own, running `filename` with `argv` as + * `Bare.argv`. If `source` is `NULL`, the contents of `filename` will instead + * be read at runtime. The arguments need only remain valid until this function + * returns. + * + * A relative `filename` names a resource of the application. On Apple + * platforms, it resolves against the resources of the application bundle, + * which extensions share with their application. On Android, it resolves + * against the code cache directory of the application context, which must then + * be given. The resources listed in `.assets`, one `/` per line, + * are extracted there from `/` in the APK before `.bundle` + * first runs, and a `NULL` source is read from the APK. + */ +int +bare_worklet_start(bare_worklet_t *worklet, const char *filename, const void *source, size_t len, int argc, const char *argv[]); + +// Suspending, resuming, waking up, or terminating a worklet is safe from any +// thread, and is a no-op if the worklet has not started or has torn down. + +/** + * Suspend the worklet, which lingers for `linger` milliseconds before going + * idle. A negative `linger` lingers for 30 seconds. On iOS, the worklet holds a + * background task for as long as it lingers, so `linger` is capped by the + * background time remaining to the application, which a negative `linger` + * lingers for instead. + */ +int +bare_worklet_suspend(bare_worklet_t *worklet, int linger); + +/** + * Resume the worklet. If it has not yet gone idle, the suspension is + * cancelled. + */ +int +bare_worklet_resume(bare_worklet_t *worklet); + +/** + * Wake up a suspended worklet and give it `deadline` milliseconds to perform + * background work before going idle again. A negative `deadline`, and the cap + * on iOS, are handled as for the `linger` of `bare_worklet_suspend()`. + */ +int +bare_worklet_wakeup(bare_worklet_t *worklet, int deadline); + +/** + * Terminate the worklet as soon as possible. The exit callback is called once + * it has torn down. + */ +int +bare_worklet_terminate(bare_worklet_t *worklet); + +/** + * Create the host end of the ipc of a worklet, which is exposed as `Bare.IPC` + * in the worklet. Fails if the worklet already has an ipc or has been + * terminated. + */ +int +bare_ipc_create(bare_worklet_t *worklet, bare_ipc_t **result); + +/** + * Close the host end, after which reads return end-of-stream and writes fail. + * Closing twice is a no-op. + */ +void +bare_ipc_close(bare_ipc_t *ipc); + +/** + * End the host end, a half-close after which `Bare.IPC` in the worklet reads + * end-of-stream once drained, while the host keeps reading. Writes fail + * afterwards. Ending twice, or after closing, is a no-op. + */ +void +bare_ipc_end(bare_ipc_t *ipc); + +/** + * Close and free the ipc. May be called before or after `bare_worklet_destroy()`, + * and from a poll callback of the ipc itself. + */ +void +bare_ipc_destroy(bare_ipc_t *ipc); + +/** + * Read up to `len` bytes, which must not be 0, into `data`. Returns the number + * of bytes read, 0 at end-of-stream, or `bare_ipc_would_block`. + */ +int +bare_ipc_read(bare_ipc_t *ipc, void *data, size_t len); + +/** + * Write `len` bytes from `data`. Returns the number of bytes written, + * `bare_ipc_would_block` if there is no room, or `bare_ipc_error` once the ipc + * is closed. + */ +int +bare_ipc_write(bare_ipc_t *ipc, const void *data, size_t len); + +/** + * Create a poll of the ipc, which calls back when it becomes readable or + * writable. Callbacks run on a thread owned by the ipc, which on Android is + * attached to the JVM, and may stop or destroy the poll or its ipc. + */ +int +bare_ipc_poll_create(bare_ipc_t *ipc, bare_ipc_poll_t **result); + +/** + * Stop and free the poll. If its callback is running on another thread, this + * waits for the callback to return. May be called from the callback itself. + */ +void +bare_ipc_poll_destroy(bare_ipc_poll_t *poll); + +/** + * Get the data that was associated with the poll by + * `bare_ipc_poll_set_data()`. + */ +void * +bare_ipc_poll_get_data(bare_ipc_poll_t *poll); + +/** + * Associate `data` with the poll, for the host to retrieve with + * `bare_ipc_poll_get_data()`, such as from the callback. + */ +void +bare_ipc_poll_set_data(bare_ipc_poll_t *poll, void *data); + +/** + * Get the ipc that the poll was created for. + */ +bare_ipc_t * +bare_ipc_poll_get_ipc(bare_ipc_poll_t *poll); + +/** + * Start polling for `events`, replacing the events and callback of a poll that + * is already started. Polls are level-triggered, so the callback is called + * again for as long as the events remain ready. + */ +int +bare_ipc_poll_start(bare_ipc_poll_t *poll, int events, bare_ipc_poll_cb cb); + +/** + * Stop polling, after which the callback is no longer called. Starting a poll + * with no `events` stops it too. + */ +int +bare_ipc_poll_stop(bare_ipc_poll_t *poll); + +#ifdef __cplusplus +} +#endif + +#endif // BARE_KIT_H diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt deleted file mode 100644 index 772ff5d..0000000 --- a/linux/CMakeLists.txt +++ /dev/null @@ -1,27 +0,0 @@ -add_library(bare_kit SHARED) - -set_target_properties( - bare_kit - PROPERTIES - C_STANDARD 11 - POSITION_INDEPENDENT_CODE ON - OUTPUT_NAME bare-kit -) - -target_link_libraries( - bare_kit - PRIVATE - bare_worklet -) - -target_include_directories( - bare_kit - INTERFACE - $ -) - -target_link_options( - bare_kit - PUBLIC - "-Wl,-z,now" # Use eager binding -) diff --git a/npm/LICENSE b/npm/LICENSE deleted file mode 100644 index 261eeb9..0000000 --- a/npm/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/npm/NOTICE b/npm/NOTICE deleted file mode 100644 index 7698d2f..0000000 --- a/npm/NOTICE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2024 Holepunch Inc - -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. diff --git a/npm/README.md b/npm/README.md deleted file mode 100644 index bae6bd7..0000000 --- a/npm/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# Bare Kit - -```sh -npm i -g bare-kit -``` - -## Usage - -```js -const BareKit = require('bare-kit') -``` - -## License - -Apache-2.0 diff --git a/npm/index.cjs b/npm/index.cjs deleted file mode 100644 index 99048d3..0000000 --- a/npm/index.cjs +++ /dev/null @@ -1,2 +0,0 @@ -/* global BareKit */ -module.exports = BareKit diff --git a/npm/index.mjs b/npm/index.mjs deleted file mode 100644 index 1be261e..0000000 --- a/npm/index.mjs +++ /dev/null @@ -1,3 +0,0 @@ -/* global BareKit */ -export default BareKit -export const IPC = BareKit.IPC diff --git a/npm/package-lock.json b/npm/package-lock.json deleted file mode 100644 index 44c7de1..0000000 --- a/npm/package-lock.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "name": "bare-kit", - "version": "0.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "bare-kit", - "version": "0.0.0", - "license": "Apache-2.0" - } - } -} diff --git a/npm/package.json b/npm/package.json deleted file mode 100644 index 574d3b6..0000000 --- a/npm/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "bare-kit", - "version": "0.0.0", - "description": "Bare for native application development", - "exports": { - ".": { - "require": "./index.cjs", - "import": "./index.mjs" - } - }, - "files": [ - "index.cjs", - "index.mjs" - ], - "repository": { - "type": "git", - "url": "git+https://github.com/holepunchto/bare-kit.git" - }, - "author": "Holepunch", - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/holepunchto/bare-kit/issues" - }, - "homepage": "https://github.com/holepunchto/bare-kit" -} diff --git a/overrides.cmake b/overrides.cmake deleted file mode 100644 index c59c758..0000000 --- a/overrides.cmake +++ /dev/null @@ -1,47 +0,0 @@ -function(add_bare_module result) - bare_module_target("." target NAME name) - - add_library(${target} OBJECT) - - set_target_properties( - ${target} - PROPERTIES - C_STANDARD 11 - CXX_STANDARD 20 - POSITION_INDEPENDENT_CODE ON - ) - - target_include_directories( - ${target} - PRIVATE - $ - ) - - set(${result} ${target}) - - return(PROPAGATE ${result}) -endfunction() - -function(add_napi_module result) - napi_module_target("." target NAME name) - - add_library(${target} OBJECT) - - set_target_properties( - ${target} - PROPERTIES - C_STANDARD 11 - CXX_STANDARD 20 - POSITION_INDEPENDENT_CODE ON - ) - - target_include_directories( - ${target} - PRIVATE - $ - ) - - set(${result} ${target}) - - return(PROPAGATE ${result}) -endfunction() diff --git a/package-lock.json b/package-lock.json index dc38df6..d1df0f5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,22 +7,19 @@ "name": "bare-kit", "license": "Apache-2.0", "dependencies": { - "bare-bundle": "^1.4.0", "bare-console": "^6.0.0", "bare-crypto": "^1.2.8", - "bare-events": "^2.4.2", "bare-fs": "^4.0.1", "bare-logger": "^2.0.0", - "bare-module": "^7.0.1", + "bare-module": "^7.5.0", "bare-module-resolve": "^1.6.2", "bare-path": "^3.0.0", "bare-stream": "^2.13.4", "bare-system-logger": "^1.0.1", - "bare-unpack": "^1.0.2", "bare-url": "^2.0.1" }, "devDependencies": { - "cmake-bare": "^1.3.0", + "cmake-bare": "^1.12.0", "cmake-bare-bundle": "^3.0.0", "cmake-fetch": "^1.1.0", "cmake-napi": "^1.1.2", @@ -46,17 +43,17 @@ } }, "node_modules/bare-abort": { - "version": "2.0.13", - "resolved": "https://registry.npmjs.org/bare-abort/-/bare-abort-2.0.13.tgz", - "integrity": "sha512-zdc8l88eB11Jsz5rDd6sCAgv2kUFXgdrZWoMlgU6JMkfAi1/uuGFC3IEHswKbIRQTk5H3T5CMuechsXYxiaHlQ==", + "version": "2.0.14", + "resolved": "https://registry.npmjs.org/bare-abort/-/bare-abort-2.0.14.tgz", + "integrity": "sha512-6H2FRP7HmZG5aDHvezZksGk/QgwTMYPvMrfYMITTsD8M39z97RYAq2gGMvuznN1vgN/Iw0f/A552pcv3dCtaTw==", "dev": true, "license": "Apache-2.0", "optional": true }, "node_modules/bare-addon-resolve": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/bare-addon-resolve/-/bare-addon-resolve-1.10.1.tgz", - "integrity": "sha512-F/SD2du8keuYSb4xipnGz5j2E6yhNdHA8ZVxtHae6h2uOrpBIjjbhXvjzKZbr5XUOzqBzh/i8GVFycj2DlFQIA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/bare-addon-resolve/-/bare-addon-resolve-1.11.0.tgz", + "integrity": "sha512-bTUBSqBjzQQzo2/iIk6KxAClZfahy38EPsJV2bPJ+p2+kS8h+hT5TE5QggpkFUrCnLL4HDTA4DDM+YiNdyol0w==", "license": "Apache-2.0", "dependencies": { "bare-module-resolve": "^1.10.0", @@ -72,9 +69,9 @@ } }, "node_modules/bare-ansi-escapes": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/bare-ansi-escapes/-/bare-ansi-escapes-2.2.3.tgz", - "integrity": "sha512-02ES4/E2RbrtZSnHJ9LntBhYkLA6lPpSEeP8iqS3MccBIVhVBlEmruF1I7HZqx5Q8aiTeYfQVeqmrU9YO2yYoQ==", + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/bare-ansi-escapes/-/bare-ansi-escapes-2.2.4.tgz", + "integrity": "sha512-IGL3L16Sp+8kPOv4+8UCav6FCQtsT7kYEqaB1A1uBesGPMEhc2fe5Je+TZ/+Sekly8ZwxvNbnlNi30X1+fqwFA==", "license": "Apache-2.0", "dependencies": { "bare-stream": "^2.6.5" @@ -89,12 +86,13 @@ } }, "node_modules/bare-assert": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/bare-assert/-/bare-assert-1.2.0.tgz", - "integrity": "sha512-c6uvgvTJBspTDxtVnPgrBKmLgcpW3Fp72NVKDLg6oT4QjQbhGtvrkHMhGYMK1sh4vjBHOBmuUalyt9hSzV37fQ==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/bare-assert/-/bare-assert-1.3.0.tgz", + "integrity": "sha512-tF3A1xa5WHzOwn2Y6Pm+mV1NGOztWUKyUQycmtMCnIcEx/0xv5MMgv2qerXQVvhkv6IZJNaEbiGBJNFD6RmunA==", "license": "Apache-2.0", "dependencies": { - "bare-inspect": "^3.1.2" + "bare-inspect": "^3.1.5", + "bare-type": "^1.3.0" } }, "node_modules/bare-buffer": { @@ -126,9 +124,9 @@ } }, "node_modules/bare-bundle-compile": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/bare-bundle-compile/-/bare-bundle-compile-1.2.2.tgz", - "integrity": "sha512-oKvqnnBjd4tVVpvDxxE0jOn33sATsnSM5DkoMqXPfQhvHm67CGf2t3UDJ/IDpxZCDH5Kb2lYVH0pDsdFPYGMxw==", + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/bare-bundle-compile/-/bare-bundle-compile-1.2.3.tgz", + "integrity": "sha512-lTVFFp1GIZczQHSWxGiM7POLVjEZ60OT1yMAYE/GnUDEcD+T+ShzviDJbXkJgA+spPwyVJBMjfq4tqF53o/VSg==", "dev": true, "license": "Apache-2.0", "peerDependencies": { @@ -136,9 +134,9 @@ } }, "node_modules/bare-bundle-id": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/bare-bundle-id/-/bare-bundle-id-1.0.2.tgz", - "integrity": "sha512-RG/y1J/s6zWmsqUIDtclXh+xxMRTh1jo/10vFL58FKhe9UESchMNkwn0Cz10o5AdA/35WR/KUGoHhIGdyCjQrg==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/bare-bundle-id/-/bare-bundle-id-1.0.3.tgz", + "integrity": "sha512-ixL4OdY9ZRcgVl9/cg3LjF1OXCsWP1vWyA5WH89PZQvj2sWXjo3Ueb9sfaz/UR0AO5GttoY40HnGBSvvQlnaLA==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -163,9 +161,9 @@ } }, "node_modules/bare-crypto": { - "version": "1.15.3", - "resolved": "https://registry.npmjs.org/bare-crypto/-/bare-crypto-1.15.3.tgz", - "integrity": "sha512-macV9lbyJTsLPRXJkBtz8ivTGEo3LCyJInLT9IB/PWJ7pRXwvHs/FP4bx/fWw+HZkiepIYCAV2cuU5CR92XWCw==", + "version": "1.15.4", + "resolved": "https://registry.npmjs.org/bare-crypto/-/bare-crypto-1.15.4.tgz", + "integrity": "sha512-4luuiLnxIJvM7ZyyW6pXbaaGoQDZcIkfcVZrPzJ3oIpdi2UIP37dROmzBWqI2lnrzfKoQlKWM8ryHmyG2svViw==", "license": "Apache-2.0", "dependencies": { "bare-assert": "^1.2.0", @@ -181,9 +179,9 @@ } }, "node_modules/bare-debug-log": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/bare-debug-log/-/bare-debug-log-2.0.0.tgz", - "integrity": "sha512-Vi42PkMQsNV9PUpx2Gl1hikshx5O9FzMJ6o9Nnopseg7qLBBK7Nl31d0RHcfwLEAfmcPApytpc0ZFfq68u22FQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/bare-debug-log/-/bare-debug-log-2.0.1.tgz", + "integrity": "sha512-bL1NxTmuRHGaT6XmqsZjLH0nElNPQJdKLjubyL7LZpqlCQqmqQfIZgQX8uqbvJ1J3NdvF7dKUgQJe5KplCZx7g==", "dev": true, "license": "Apache-2.0", "optional": true, @@ -192,14 +190,14 @@ } }, "node_modules/bare-dns": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/bare-dns/-/bare-dns-2.2.1.tgz", - "integrity": "sha512-76kta7f4YMiXwhdlK1q8AFnVvSlZ5yv4FL4AH83KoTRErgj0Ttm6Jo9993+gWEWQfl7VZTHtihPozstlknXszw==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/bare-dns/-/bare-dns-2.3.1.tgz", + "integrity": "sha512-NRGJE+OkJV2v3JEdAC2hBdUSNgeyOS9gUpLNLuVOT0aDmB/IZ59lK+zotKJ5yFnz6rZ0/4y3+9MOOLkemGv1Ig==", "dev": true, "license": "Apache-2.0", "optional": true, "engines": { - "bare": ">=1.7.0" + "bare": ">=1.33.0" }, "peerDependencies": { "bare-buffer": "*" @@ -252,18 +250,18 @@ } }, "node_modules/bare-format": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/bare-format/-/bare-format-1.0.2.tgz", - "integrity": "sha512-GswdhnOnP9QtwRbrf4wLApw5widkaLMsLe2XOs35fQD2YfEN1ApoGka+cZ7PfvzxMgfYXmMhj/2OGlVn5/Dxgw==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/bare-format/-/bare-format-1.0.3.tgz", + "integrity": "sha512-E/LJdhZ06VSWLlquAjJKZM2B+vLr7lluthTQ6H3H0KvrHMd+Zmdyy6+bW1IITd0x5tYa+C5AYSggyY5ojL9+sg==", "license": "Apache-2.0", "dependencies": { "bare-inspect": "^3.0.0" } }, "node_modules/bare-fs": { - "version": "4.8.1", - "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.8.1.tgz", - "integrity": "sha512-N1nnXdHZAOSstz0XiHikGS4HGMH4CnSwhqWdGQQMqqdvp4Jybm9sE3R1WVnpWVd4SFkc8ryPDBLViNLwiEqECg==", + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.8.4.tgz", + "integrity": "sha512-MPC2eyrpbk3A873sK4y6rk+Iv4o2enxTjHZ8zH3HO0mjrpm5XjnguY2XmfidIsDV6vnjpbMBKUAJpV0ISD2SsQ==", "license": "Apache-2.0", "dependencies": { "bare-events": "^2.5.4", @@ -319,22 +317,23 @@ "license": "Apache-2.0" }, "node_modules/bare-module": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/bare-module/-/bare-module-7.0.3.tgz", - "integrity": "sha512-R5G6DvQrpctvD7Xw80M0C9mDxUSEIK7IEcA+EpVXmdVEQ5kInPuAst14WYzhRvoAOQg1/HrnYhmvIiJh7aZ5Zw==", + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/bare-module/-/bare-module-7.5.0.tgz", + "integrity": "sha512-TvcHjJFyaJuLRNhSQosJBsj99NEki86M1CRsp9yqqhH+iLuG95hingxVnqlIzq11TO0nK0IdiO2FthM4aZ3UFw==", "license": "Apache-2.0", "dependencies": { "bare-bundle": "^1.11.0", - "bare-module-lexer": "^1.6.1", - "bare-module-resolve": "^1.12.3", - "bare-module-traverse": "~2.5.5", + "bare-module-lexer": "^1.7.0", + "bare-module-resolve": "^1.12.6", + "bare-module-traverse": "~2.7.0", "bare-path": "^3.0.0", "bare-type-stripper": "^0.1.2", "bare-url": "^2.0.1", + "bare-wasm-abi": "^0.1.0", "promaphore": "^1.0.0" }, "engines": { - "bare": ">=1.32.0" + "bare": ">=1.35.0" }, "peerDependencies": { "bare-buffer": "*" @@ -346,9 +345,9 @@ } }, "node_modules/bare-module-lexer": { - "version": "1.6.7", - "resolved": "https://registry.npmjs.org/bare-module-lexer/-/bare-module-lexer-1.6.7.tgz", - "integrity": "sha512-ImbCteBVEc5JKNV2M6V6s23mAunzl+hDolPWfaexYqBMiN7JG4yDy6Dg5ue2N61U8l2mlvgZuefVl13Yd06lDA==", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/bare-module-lexer/-/bare-module-lexer-1.7.0.tgz", + "integrity": "sha512-LD5eiVhDyiMRfMtxK3E+0SeL95nkLNl37YUccXWEaErmfkJi596OECtUoH3X+YPomthwW2oQEch9c7aOOJ4ePA==", "license": "Apache-2.0", "dependencies": { "require-addon": "^1.0.2" @@ -367,9 +366,9 @@ } }, "node_modules/bare-module-resolve": { - "version": "1.12.5", - "resolved": "https://registry.npmjs.org/bare-module-resolve/-/bare-module-resolve-1.12.5.tgz", - "integrity": "sha512-VOncxVvVk8SQVw9vhcBnoTJD/74aR5DgdRPCm0gQ7uB5MsWpBJnoCeJrwEHKiz09O83ndf3NTjsz3LEuFxAq5A==", + "version": "1.12.6", + "resolved": "https://registry.npmjs.org/bare-module-resolve/-/bare-module-resolve-1.12.6.tgz", + "integrity": "sha512-tsoOqHmtF6VmNX4LYDBZwvQVkSmEagnbykNjK31LMxz/amyKfjCs4K976n7uJd1bvWfxbpLQ3Fy7qq8an6jR6Q==", "license": "Apache-2.0", "dependencies": { "bare-semver": "^1.0.0" @@ -384,12 +383,13 @@ } }, "node_modules/bare-module-traverse": { - "version": "2.5.6", - "resolved": "https://registry.npmjs.org/bare-module-traverse/-/bare-module-traverse-2.5.6.tgz", - "integrity": "sha512-BQ/rsuBvcC3EnKJAkyd1fbpypRgc3GfqI9/7y6kDoW4I2HY91lhBvhFj7CXvyRWmvVcaGvgPcmL9vCl6BHIH7g==", + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/bare-module-traverse/-/bare-module-traverse-2.7.2.tgz", + "integrity": "sha512-cvVrB5vcIc7QakOq0oXhuu2l2yejff1pV59nA/rk21xsFSm2zMl3dC7opzRwowjisliawTUBP6VoakqBEKQUQA==", "license": "Apache-2.0", "dependencies": { "bare-addon-resolve": "^1.5.0", + "bare-bundle": "^1.11.0", "bare-mime": "^1.0.0", "bare-module-lexer": "^1.6.0", "bare-module-resolve": "^1.7.0" @@ -419,16 +419,16 @@ } }, "node_modules/bare-pack": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/bare-pack/-/bare-pack-2.2.2.tgz", - "integrity": "sha512-4id2zXMNlQSDyTD1ynbvZBDEVebkqU8CkgJQv01LDxF0PAtMcJ+4LKYXQbz+rmkJIchvSuMd2v62dYrOKf2zBQ==", + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/bare-pack/-/bare-pack-3.0.2.tgz", + "integrity": "sha512-wGwpPaXRuu5zE2SrEV4nZReh36q0Ul3C0JdMR/M7Du2Vc4IrgHr6/ok84bpeAGmB6iCAcDPztiPu5N8f9LeKaw==", "dev": true, "license": "Apache-2.0", "dependencies": { "bare-bundle": "^1.8.3", "bare-bundle-id": "^1.0.0", "bare-fs": "^4.2.1", - "bare-module-traverse": "~2.5.0", + "bare-module-traverse": "~2.7.0", "bare-path": "^3.0.0", "paparam": "^1.5.0", "promaphore": "^1.0.0" @@ -456,9 +456,9 @@ "license": "Apache-2.0" }, "node_modules/bare-pipe": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/bare-pipe/-/bare-pipe-4.3.1.tgz", - "integrity": "sha512-3P4MYTgOys1Bbz5dgWzwfroNOOl8x1zWJHTHVlwsojThhV/uJPRf+qFrYYBOnI0vQiJJLJtHlw8a4Osj/kcsJQ==", + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/bare-pipe/-/bare-pipe-4.4.0.tgz", + "integrity": "sha512-fUOLSyMvXvpOoQq/3VN/bmb/mPsfg6JQllLt3cOWbRMEX9uKvq1hSafdYlu4yb7JYIwA8P/ttdIh0RaOy0fGMg==", "dev": true, "license": "Apache-2.0", "optional": true, @@ -565,15 +565,15 @@ } }, "node_modules/bare-structured-clone": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/bare-structured-clone/-/bare-structured-clone-1.6.0.tgz", - "integrity": "sha512-AZjEERyqF7kAuudlmgrweT2KwwWM0LsGG4Gx/bWyFwJrKU7E3wNG8c09z2DIrdw93p3vDtfOX8fyHOcXfy5m+g==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/bare-structured-clone/-/bare-structured-clone-2.0.1.tgz", + "integrity": "sha512-F/n/etzjf4YlW4OCF0kpe0H6UOcCXZg0LrPMCY2dP9fg2R7fME5crkmQlM1Hl62iKipMQFaT9S2eSyx0tBCJ8g==", "dev": true, "license": "Apache-2.0", "optional": true, "dependencies": { "bare-buffer": "^3.6.0", - "bare-type": "^1.1.0", + "bare-type": "^1.3.0", "bare-url": "^2.4.0", "compact-encoding": "^3.0.1" }, @@ -594,9 +594,9 @@ } }, "node_modules/bare-subprocess": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/bare-subprocess/-/bare-subprocess-6.1.0.tgz", - "integrity": "sha512-8L6KtbmreDy4Fc1BdDqaDo9fg0nbedUmTSFQxYPV0uHIM2BBAX8+E0LyMDKgkk0I+mlKto80WYzOnIhT8VDdOg==", + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/bare-subprocess/-/bare-subprocess-6.2.2.tgz", + "integrity": "sha512-kPyg/+LfML88uypOlbe19pRXsPFKtXXDEI5eEAFqGlmvO9cL/XsIZ+OAWKoNOSsomqcxM1rsvnF/uRE9NFaBLQ==", "dev": true, "license": "Apache-2.0", "optional": true, @@ -605,7 +605,7 @@ "bare-events": "^2.5.4", "bare-os": "^3.0.1", "bare-pipe": "^4.2.0", - "bare-structured-clone": "^1.5.2", + "bare-structured-clone": "^2.0.0", "bare-tcp": "^2.4.1", "bare-url": "^2.2.2" }, @@ -622,9 +622,9 @@ } }, "node_modules/bare-system-logger": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/bare-system-logger/-/bare-system-logger-1.0.5.tgz", - "integrity": "sha512-Xnjk5jFJWKrfVfHfusHwUpfiPmZqWUm9gaCUolTlN1pxxf7yDn7mhC+pr885j6VVSLzZwfZYi9nywVI+VakxVg==", + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/bare-system-logger/-/bare-system-logger-1.0.6.tgz", + "integrity": "sha512-wAyqwfeQ4wVPHnVQTCsDE/kAHRd51XI1LqzgkJegRDX8AFilo1NGprF/5XpNz5uB4MV+hb2O2fe5v3IuCgMTDA==", "license": "Apache-2.0", "dependencies": { "bare-logger": "^2.0.0" @@ -655,9 +655,9 @@ } }, "node_modules/bare-tty": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/bare-tty/-/bare-tty-5.2.1.tgz", - "integrity": "sha512-vH9ggdu6q+HilCKcYCfSzwuN2QaR4+gGP+JiYN5zKMhMI6tKeKnZMCuE/AJoF9lbSo0FriPdZoKA5bO2b0Mk3w==", + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/bare-tty/-/bare-tty-5.2.2.tgz", + "integrity": "sha512-oyrepHCXHn4uLNCW1BKa61340ymtiAnvdVaW3qOot/yqmBWJqDSOqVBzLCeroMsZKuaODaIrAGVpTxXWxIZskg==", "dev": true, "license": "Apache-2.0", "optional": true, @@ -671,12 +671,12 @@ } }, "node_modules/bare-type": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/bare-type/-/bare-type-1.1.1.tgz", - "integrity": "sha512-5HwbjDbnYr+Lwu5I59IqwOFcRcVo4jxo408t42gKhKnikw0ojwyPXPlx58AQP4dR2VvGw57ppX/qxYCn60Wujw==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/bare-type/-/bare-type-1.4.0.tgz", + "integrity": "sha512-6anDbVGruQLK8m6zxlCPNkUuxXnzChT1aOmJbFRjEGn8MWZqviFP6vGi9NAnG8aRXyRAfXIGLlBJwYGa4Ylcug==", "license": "Apache-2.0", "engines": { - "bare": ">=1.2.0" + "bare": ">=1.32.0" } }, "node_modules/bare-type-stripper": { @@ -700,35 +700,19 @@ } } }, - "node_modules/bare-unpack": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/bare-unpack/-/bare-unpack-1.1.3.tgz", - "integrity": "sha512-b+OFTi74dsMaVQy9w90U6WMqhVBcx5hONJnFbOSfhTefG/9OuY6ZxU3IvybVa5/i3edzboa7rebaMG25K6/kAA==", - "license": "Apache-2.0", - "dependencies": { - "bare-bundle": "^1.8.3", - "bare-fs": "^4.2.3", - "bare-path": "^3.0.0", - "paparam": "^1.8.5", - "promaphore": "^1.0.0" - }, - "bin": { - "bare-unpack": "bin.js" - } - }, "node_modules/bare-url": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.4.tgz", - "integrity": "sha512-Gxa7UVWBr0/edU1b+TJhn/AZvMQUj9OGspvYsaTYQrAbZA4BOTZGL3LiZxvD+CeMlDH4juwD84+eTAp/bLYW5g==", + "version": "2.5.5", + "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.5.tgz", + "integrity": "sha512-iM9qJCruvpt2rPaLsrumVDru9pogI7PHziHIa9kTNRFt8C8HuSa+kI9kFezK+NvHEFnnz71rKGZ1EAilq/3V/Q==", "license": "Apache-2.0", "dependencies": { "bare-path": "^3.0.0" } }, "node_modules/bare-utils": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/bare-utils/-/bare-utils-1.6.0.tgz", - "integrity": "sha512-WhQEIkkAxkSnW7u1QgrI0AfNm5JpMruETXeYsb5qnkBJ0TTfNKygZmsh6rkoHBANaV+C/7Jed7bJP9OmEHG7rQ==", + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/bare-utils/-/bare-utils-1.6.1.tgz", + "integrity": "sha512-k3yAod0yDg/qctLnbhefmtwdufkzbpDFqmcympxenmRwGk7euZ0ll6gha2bC6rM230G5XS5BHyzcHyYSuXcfzQ==", "dev": true, "license": "Apache-2.0", "optional": true, @@ -741,10 +725,45 @@ "bare-type": "^1.0.6" } }, + "node_modules/bare-wasi": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/bare-wasi/-/bare-wasi-0.1.2.tgz", + "integrity": "sha512-LXW+ReMSkdZocLCWPMeVmG2AYCz07Kf+moIXWGSi9m7En1xfkIb7enZd3irSvmMjfJhhASgiBj0sLyVzmU/vmg==", + "license": "Apache-2.0", + "dependencies": { + "bare-hrtime": "^2.1.2", + "bare-wasm": "^0.1.0" + }, + "peerDependencies": { + "bare-directory": "*" + }, + "peerDependenciesMeta": { + "bare-directory": { + "optional": true + } + } + }, + "node_modules/bare-wasm": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/bare-wasm/-/bare-wasm-0.1.1.tgz", + "integrity": "sha512-fkulwnM0ccGPIC369d3tGH95hZiG54AE4PMmSUcJpasmiBM6+HcKnpQOVCb0BeuwXzg3KJdxVhPik3KWo/zM9g==", + "license": "Apache-2.0" + }, + "node_modules/bare-wasm-abi": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/bare-wasm-abi/-/bare-wasm-abi-0.1.1.tgz", + "integrity": "sha512-55LoMjZ9bmoKTUe2nPIP1yKgIS2Usb2rPJEesF9rhjjKpsNoHSzG7CS54zPLTmhY25Te+6iqrTH+AkTibUv+Fg==", + "license": "Apache-2.0", + "dependencies": { + "bare-type": "^1.4.0", + "bare-wasi": "^0.1.0", + "bare-wasm": "^0.1.0" + } + }, "node_modules/cmake-bare": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/cmake-bare/-/cmake-bare-1.9.0.tgz", - "integrity": "sha512-ZMtkwOBmHO+4thh7Q10OBDg5KwE/fmBA4mJBbPVt+JnevxHZavKhXBTDKjNp+gyHt/bsP+YlUB5h4IxwgV0Q+Q==", + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/cmake-bare/-/cmake-bare-1.12.0.tgz", + "integrity": "sha512-AkRij7IpB4N4V2XBomA+OUbwe8/NyzDpGIsX+CElgXU3CqPzsAwOHgM70+BgGXrcbgadUQZNyY9noNs7OZ4IxA==", "dev": true, "license": "Apache-2.0", "workspaces": [ @@ -756,16 +775,16 @@ } }, "node_modules/cmake-bare-bundle": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/cmake-bare-bundle/-/cmake-bare-bundle-3.0.0.tgz", - "integrity": "sha512-fQcgIqG08PoYbvAlGy50oecFqQngx0VIxlkuZtq0vl8G2eYM+ADwPVEjzBgvAmQUYZHceV3Hszeifp8L/1lAkQ==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/cmake-bare-bundle/-/cmake-bare-bundle-3.0.1.tgz", + "integrity": "sha512-qVO8YdkGdnkXr/rv63MuY78ARlPatIkIMgCPQ5hE5CTf1IH/N4R6PQCTF/ETjX/GEkGxIcGOOyNxU90nBoALxQ==", "dev": true, "license": "Apache-2.0", "dependencies": { "bare-bundle": "^1.8.0", "bare-bundle-compile": "^1.0.0", "bare-module-traverse": "^2.0.0", - "bare-pack": "^2.0.0", + "bare-pack": "^3.0.0", "cmake-bare": "^1.1.4", "include-static": "^1.1.0" } @@ -778,23 +797,23 @@ "license": "Apache-2.0" }, "node_modules/cmake-napi": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/cmake-napi/-/cmake-napi-1.3.0.tgz", - "integrity": "sha512-LOlsTAqR4Ykf7MXF4FSAnPLxJ5+pDL2S8KiLX8UwStTQQN9iq925BIFEMIyNbc3YvLhxrfJkpb/6WLjKpnOO3A==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/cmake-napi/-/cmake-napi-1.3.2.tgz", + "integrity": "sha512-uoY4erlFpWF8qPunyeHR2G/smsYp7bF0zebu+fai3/+yqsyTW+ad6Rrpm9gZ6Ef5h3kMcywia/b6zfxZ0xSB0Q==", "dev": true, "license": "Apache-2.0" }, "node_modules/cmake-npm": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/cmake-npm/-/cmake-npm-1.1.2.tgz", - "integrity": "sha512-CfN53Ov9usNBeaIsr8TtEQwwXeRZkJWZSoGe0qybr9bojxGlwTdxHk8LQwJFNypsSgFoYyOWUMjKGuahsiGifA==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/cmake-npm/-/cmake-npm-1.2.0.tgz", + "integrity": "sha512-HNgrK1wDdWTs1jfkcdeWDIffgOA9tZNG1pNJcWp0LOO12mHZyyslXjYYLxD/4KD5xtWJwCu0bBUJ5ZN9GpojOQ==", "dev": true, "license": "Apache-2.0" }, "node_modules/compact-encoding": { - "version": "3.5.0", - "resolved": "https://registry.npmjs.org/compact-encoding/-/compact-encoding-3.5.0.tgz", - "integrity": "sha512-X7yaWh0NNMVB2YXAWSTWjYU3WXvDTniKxbtQlisbXOVutIE6awd+zCQdNqScTjIXv9m9orqdlri+oaWWsKqTuA==", + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/compact-encoding/-/compact-encoding-3.5.2.tgz", + "integrity": "sha512-rgGcWdfxyuLwJHMUXI0OrYGpJe3VN4RZyovbxWVlxPYIsUZutOTfP3shmDyDi/iaybwcxMsTJDDuxQa4xRG0RQ==", "dev": true, "license": "Apache-2.0", "optional": true, @@ -828,9 +847,9 @@ } }, "node_modules/lunte": { - "version": "1.8.4", - "resolved": "https://registry.npmjs.org/lunte/-/lunte-1.8.4.tgz", - "integrity": "sha512-u6cjFWSDbPB8Qm/fM/9uIXLcNf+wa91t02uHjqwVGPFdP3VAU2g345iTeI1Sv6XY4PxpwvcV0HkhG/St3dNfAQ==", + "version": "1.8.6", + "resolved": "https://registry.npmjs.org/lunte/-/lunte-1.8.6.tgz", + "integrity": "sha512-RdCVBATCV9QGC9t9Moo0SkeG1KNsglg14nOjZz/mupTy62dhAi2O3Cwe56HgwUt1utBVnb/+4i/oBVpSVgqZUw==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -879,15 +898,16 @@ } }, "node_modules/paparam": { - "version": "1.13.0", - "resolved": "https://registry.npmjs.org/paparam/-/paparam-1.13.0.tgz", - "integrity": "sha512-WV8vCnEBPKcSSEIDSaAetppO+C0+OUJ6gjO1BGbhvIp2jc8zfV9C/8NARjEGgnUo5DDwdNsGOrFTZKLFTTeB0A==", + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/paparam/-/paparam-1.14.0.tgz", + "integrity": "sha512-WQshqM/4Itr6jXK+sRku9oOuhkX9mV9i2ZALusT5H9QWAlZ8JVe5V+SI92xEyRsmtM30sv1NcMvnokPGFn/Aew==", + "dev": true, "license": "Apache-2.0" }, "node_modules/prettier": { - "version": "3.9.7", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.7.tgz", - "integrity": "sha512-T3mF5P7HFzZVLDQuCUNtJj6WK1pcpLMweMNUVwGb01bLNkH9AkKxtZvmInw8K6bnn2O3d6/5RHl6zSHiBAD0Og==", + "version": "3.9.10", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.10.tgz", + "integrity": "sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==", "dev": true, "license": "MIT", "bin": { @@ -929,9 +949,9 @@ } }, "node_modules/sodium-native": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/sodium-native/-/sodium-native-5.1.0.tgz", - "integrity": "sha512-3RxgyWyJlhTsABPnJVpCI5CoTDANZTqqFrEPqr+kjfnRaBihpVtMUE3yTF40ukdoB1APXeoBNKF3MzZAIHg39g==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/sodium-native/-/sodium-native-5.2.0.tgz", + "integrity": "sha512-ntJqNSc9bWmWqcJkx8NA5eS0HUwQnmDlluUzoKCOQUWey8i7LXptk+E/qo2T2RPO9uK2br+3N0zYQme8qPXG+g==", "dev": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index acac130..4a0536c 100644 --- a/package.json +++ b/package.json @@ -17,22 +17,19 @@ }, "homepage": "https://github.com/holepunchto/bare-kit#readme", "dependencies": { - "bare-bundle": "^1.4.0", "bare-console": "^6.0.0", "bare-crypto": "^1.2.8", - "bare-events": "^2.4.2", "bare-fs": "^4.0.1", "bare-logger": "^2.0.0", - "bare-module": "^7.0.1", + "bare-module": "^7.5.0", "bare-module-resolve": "^1.6.2", "bare-path": "^3.0.0", "bare-stream": "^2.13.4", "bare-system-logger": "^1.0.1", - "bare-unpack": "^1.0.2", "bare-url": "^2.0.1" }, "devDependencies": { - "cmake-bare": "^1.3.0", + "cmake-bare": "^1.12.0", "cmake-bare-bundle": "^3.0.0", "cmake-fetch": "^1.1.0", "cmake-napi": "^1.1.2", diff --git a/prebuilds/.gitignore b/prebuilds/.gitignore deleted file mode 100644 index a0991ff..0000000 --- a/prebuilds/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -* -!.gitignore -!Makefile diff --git a/prebuilds/Makefile b/prebuilds/Makefile deleted file mode 100644 index fde1dca..0000000 --- a/prebuilds/Makefile +++ /dev/null @@ -1,96 +0,0 @@ -%.framework: %.framework.tar - tar -xf $< --directory $(dir $<) - -%.framework: - rm -rf $@ - mkdir -p $(dir $@) - cp -a $< $@ - lipo -create -output $@/$(basename $(notdir $@)) $(addsuffix /$(basename $(notdir $@)),$^) - -%.xcframework: - rm -rf $@ - xcodebuild -create-xcframework -output $@ $(addprefix -framework , $^) - -%: %-release.aar - rm -rf $@ - mkdir -p $@ - unzip -q $< -d $@ - -all: \ - apple/BareKit.xcframework \ - apple-javascriptcore/BareKit.xcframework \ - darwin/BareKit.xcframework \ - darwin-javascriptcore/BareKit.xcframework \ - ios/BareKit.xcframework \ - ios-javascriptcore/BareKit.xcframework \ - android/bare-kit \ - linux/x64/libbare-kit.so \ - linux/arm64/libbare-kit.so \ - win32/x64/bare-kit.dll \ - win32/x64/bare-kit.lib \ - win32/x64/bare-kit.def \ - win32/arm64/bare-kit.dll \ - win32/arm64/bare-kit.lib \ - win32/arm64/bare-kit.def - -apple/BareKit.xcframework: \ - darwin/BareKit.framework \ - ios/BareKit.framework \ - ios-simulator/BareKit.framework - -apple-javascriptcore/BareKit.xcframework: \ - darwin-javascriptcore/BareKit.framework \ - ios-javascriptcore/BareKit.framework \ - ios-simulator-javascriptcore/BareKit.framework - -darwin/BareKit.xcframework: \ - darwin/BareKit.framework - -darwin/BareKit.framework: \ - darwin-arm64/BareKit.framework \ - darwin-x64/BareKit.framework - -darwin-javascriptcore/BareKit.xcframework: \ - darwin-javascriptcore/BareKit.framework - -darwin-javascriptcore/BareKit.framework: \ - darwin-arm64-javascriptcore/BareKit.framework \ - darwin-x64-javascriptcore/BareKit.framework - -ios/BareKit.xcframework: \ - ios/BareKit.framework \ - ios-simulator/BareKit.framework - -ios/BareKit.framework: \ - ios-arm64/BareKit.framework - -ios-simulator/BareKit.framework: \ - ios-arm64-simulator/BareKit.framework \ - ios-x64-simulator/BareKit.framework - -ios-javascriptcore/BareKit.xcframework: \ - ios-javascriptcore/BareKit.framework \ - ios-simulator-javascriptcore/BareKit.framework - -ios-javascriptcore/BareKit.framework: \ - ios-arm64-javascriptcore/BareKit.framework - -ios-simulator-javascriptcore/BareKit.framework: \ - ios-arm64-simulator-javascriptcore/BareKit.framework \ - ios-x64-simulator-javascriptcore/BareKit.framework - -linux/%/libbare-kit.so: linux-%/libbare-kit.so - mkdir -p $(dir $@) - cp -a $< $@ - -win32/%/bare-kit.dll: win32-%/bare-kit.dll - mkdir -p $(dir $@) - cp -a $< $@ - -win32/%/bare-kit.lib: win32-%/bare-kit.lib - mkdir -p $(dir $@) - cp -a $< $@ - -win32/%/bare-kit.def: win32-%/bare-kit.def - mkdir -p $(dir $@) - cp -a $< $@ diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index 82bb6e5..0000000 --- a/settings.gradle +++ /dev/null @@ -1,16 +0,0 @@ -pluginManagement { - repositories { - google() - mavenCentral() - } -} - -dependencyResolutionManagement { - repositories { - google() - mavenCentral() - } -} - -include ":bare-kit" -project(":bare-kit").projectDir = file("android") diff --git a/shared/CMakeLists.txt b/shared/CMakeLists.txt deleted file mode 100644 index 29ccd9a..0000000 --- a/shared/CMakeLists.txt +++ /dev/null @@ -1,152 +0,0 @@ -add_bare_bundle( - bare_worklet_bundle - ENTRY shared/worklet.js - OUT shared/worklet.bundle.h - BUILTINS shared/builtins.json - WORKING_DIRECTORY .. -) - -add_library(bare_worklet OBJECT) - -set_target_properties( - bare_worklet - PROPERTIES - C_STANDARD 11 - POSITION_INDEPENDENT_CODE ON -) - -target_sources( - bare_worklet - PRIVATE - context.h - events.h - ipc.h - ipc.c - queue.h - queue.c - worklet.c - worklet.bundle.h - worklet.h -) - -if(ANDROID) - target_sources( - bare_worklet - PRIVATE - android/context.c - android/events.c - android/jvm.c - android/jvm.h - ) -else() - target_sources( - bare_worklet - PRIVATE - context.c - events.c - ) -endif() - -target_include_directories( - bare_worklet - PUBLIC - $ -) - -if(APPLE) - target_sources( - bare_worklet - PRIVATE - apple/ipc.h - apple/ipc.m - apple/suspension.h - apple/suspension.m - ) - - if(IOS) - target_link_libraries( - bare_worklet - PUBLIC - "-framework UIKit" - ) - - target_compile_definitions( - bare_worklet - PUBLIC - BARE_KIT_IOS - ) - else() - target_compile_definitions( - bare_worklet - PUBLIC - BARE_KIT_DARWIN - ) - endif() -endif() - -if(ANDROID) - target_sources( - bare_worklet - PRIVATE - android/ipc.c - android/ipc.h - android/suspension.c - android/suspension.h - ) - - target_link_libraries( - bare_worklet - PRIVATE - android - ) - - target_compile_definitions( - bare_worklet - PUBLIC - BARE_KIT_ANDROID - ) -endif() - -if(LINUX) - target_sources( - bare_worklet - PRIVATE - uv/ipc.c - uv/ipc.h - linux/suspension.c - linux/suspension.h - ) - - target_compile_definitions( - bare_worklet - PUBLIC - BARE_KIT_LINUX - ) -endif() - -if(WIN32) - target_sources( - bare_worklet - PRIVATE - uv/ipc.c - uv/ipc.h - win32/suspension.c - win32/suspension.h - ) - - target_compile_definitions( - bare_worklet - PUBLIC - BARE_KIT_WINDOWS - ) -endif() - -target_link_libraries( - bare_worklet - INTERFACE - $ - PUBLIC - rlimit_static -) - -link_bare_modules(bare_worklet WORKING_DIRECTORY ..) diff --git a/shared/android/context.c b/shared/android/context.c deleted file mode 100644 index 6821754..0000000 --- a/shared/android/context.c +++ /dev/null @@ -1,16 +0,0 @@ -#include -#include - -#include "../context.h" -#include "jvm.h" - -void -bare_kit__publish_context(bare_t *bare) { - int err; - - JavaVM *vm = bare_kit__jvm_get(); - assert(vm != NULL); - - err = bare_context_set(bare, "bare.android.jvm.v1", vm, NULL); - assert(err == 0); -} diff --git a/shared/android/events.c b/shared/android/events.c deleted file mode 100644 index b27afd3..0000000 --- a/shared/android/events.c +++ /dev/null @@ -1,90 +0,0 @@ -#include -#include -#include - -#include "../events.h" -#include "jvm.h" - -static void -bare_kit__set_context_class_loader(JNIEnv *env) { - jclass thread_class = (*env)->FindClass(env, "java/lang/Thread"); - assert(thread_class != NULL); - - jmethodID current_thread = (*env)->GetStaticMethodID(env, thread_class, "currentThread", "()Ljava/lang/Thread;"); - assert(current_thread != NULL); - - jobject thread = (*env)->CallStaticObjectMethod(env, thread_class, current_thread); - assert(thread != NULL); - assert(!(*env)->ExceptionCheck(env)); - - jclass activity_thread_class = (*env)->FindClass(env, "android/app/ActivityThread"); - assert(activity_thread_class != NULL); - - jmethodID current_application = (*env)->GetStaticMethodID(env, activity_thread_class, "currentApplication", "()Landroid/app/Application;"); - assert(current_application != NULL); - - jobject application = (*env)->CallStaticObjectMethod(env, activity_thread_class, current_application); - assert(application != NULL); - assert(!(*env)->ExceptionCheck(env)); - - jclass application_class = (*env)->GetObjectClass(env, application); - assert(application_class != NULL); - - jmethodID get_class_loader = (*env)->GetMethodID(env, application_class, "getClassLoader", "()Ljava/lang/ClassLoader;"); - assert(get_class_loader != NULL); - - jobject class_loader = (*env)->CallObjectMethod(env, application, get_class_loader); - assert(class_loader != NULL); - assert(!(*env)->ExceptionCheck(env)); - - jmethodID set_context_class_loader = (*env)->GetMethodID(env, thread_class, "setContextClassLoader", "(Ljava/lang/ClassLoader;)V"); - assert(set_context_class_loader != NULL); - - (*env)->CallVoidMethod(env, thread, set_context_class_loader, class_loader); - assert(!(*env)->ExceptionCheck(env)); - - (*env)->DeleteLocalRef(env, class_loader); - (*env)->DeleteLocalRef(env, application_class); - (*env)->DeleteLocalRef(env, application); - (*env)->DeleteLocalRef(env, activity_thread_class); - (*env)->DeleteLocalRef(env, thread); - (*env)->DeleteLocalRef(env, thread_class); -} - -void -bare_kit__on_thread_enter(bare_worklet_state_t *state) { - int err; - - JavaVM *vm = bare_kit__jvm_get(); - assert(vm != NULL); - - JNIEnv *env; - err = (*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6); - assert(err == JNI_EDETACHED); - - JavaVMAttachArgs args = { - JNI_VERSION_1_6, - "bare-worklet", - NULL, - }; - - err = (*vm)->AttachCurrentThread(vm, &env, &args); - assert(err == JNI_OK); - - bare_kit__set_context_class_loader(env); -} - -void -bare_kit__on_thread_exit(bare_worklet_state_t *state) { - int err; - - JavaVM *vm = bare_kit__jvm_get(); - assert(vm != NULL); - - JNIEnv *env; - err = (*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6); - assert(err == JNI_OK); - - err = (*vm)->DetachCurrentThread(vm); - assert(err == JNI_OK); -} diff --git a/shared/android/ipc.c b/shared/android/ipc.c deleted file mode 100644 index be5e1d5..0000000 --- a/shared/android/ipc.c +++ /dev/null @@ -1,143 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#include "ipc.h" - -// The looper wakes on a file descriptor, so the signal is an eventfd. -typedef struct { - int wake; -} bare_ipc_signal_t; - -int -bare_ipc__signal_init(bare_ipc_t *ipc) { - bare_ipc_signal_t *signal = malloc(sizeof(bare_ipc_signal_t)); - - if (signal == NULL) return -1; - - // The count persists until read, so a poll started after a signal still wakes. - signal->wake = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK); - - if (signal->wake < 0) { - free(signal); - - return -1; - } - - ipc->signal = signal; - - return 0; -} - -void -bare_ipc__signal(bare_ipc_t *ipc) { - bare_ipc_signal_t *signal = (bare_ipc_signal_t *) ipc->signal; - - uint64_t value = 1; - - ssize_t written = write(signal->wake, &value, sizeof(value)); - assert(written == sizeof(value)); -} - -void -bare_ipc__signal_destroy(bare_ipc_t *ipc) { - bare_ipc_signal_t *signal = (bare_ipc_signal_t *) ipc->signal; - - int err = close(signal->wake); - assert(err == 0); - - free(signal); - - ipc->signal = NULL; -} - -int -bare_ipc_poll_init(bare_ipc_poll_t *poll, bare_ipc_t *ipc) { - poll->ipc = ipc; - poll->events = 0; - poll->cb = NULL; - poll->data = NULL; - poll->looper = ALooper_forThread(); - - ALooper_acquire(poll->looper); - - ipc->poll = poll; - - return 0; -} - -// The fd registration belongs to the looper's thread. Changed from elsewhere, it -// races the callback, which may then run on a freed poll. -static void -bare_ipc__assert_looper(bare_ipc_poll_t *poll) { - assert(ALooper_forThread() == poll->looper); -} - -void -bare_ipc_poll_destroy(bare_ipc_poll_t *poll) { - bare_ipc__assert_looper(poll); - - int err; - err = bare_ipc_poll_stop(poll); - assert(err == 0); - - poll->ipc->poll = NULL; - - ALooper_release(poll->looper); -} - -static int -bare_ipc__on_wake(int fd, int events, void *data) { - bare_ipc_poll_t *poll = (bare_ipc_poll_t *) data; - - uint64_t value; - - ssize_t read_len = read(fd, &value, sizeof(value)); - assert(read_len == sizeof(value) || errno == EAGAIN); - - bare_ipc__dispatch(poll->ipc); - - return 1; // Don't deregister the file descriptor -} - -int -bare_ipc_poll_start(bare_ipc_poll_t *poll, int events, bare_ipc_poll_cb cb) { - if (events == 0) return bare_ipc_poll_stop(poll); - - bare_ipc__assert_looper(poll); - - bare_ipc_t *ipc = poll->ipc; - - bare_ipc_signal_t *signal = (bare_ipc_signal_t *) ipc->signal; - - if (poll->events == 0) { - int err = ALooper_addFd(poll->looper, signal->wake, ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, bare_ipc__on_wake, (void *) poll); - assert(err == 1); - } - - poll->events = events; - poll->cb = cb; - - // Level-triggered: signal once in case the events are already ready. - bare_ipc__signal(ipc); - - return 0; -} - -int -bare_ipc_poll_stop(bare_ipc_poll_t *poll) { - bare_ipc__assert_looper(poll); - - bare_ipc_signal_t *signal = (bare_ipc_signal_t *) poll->ipc->signal; - - if (poll->events != 0) ALooper_removeFd(poll->looper, signal->wake); - - poll->events = 0; - poll->cb = NULL; - - return 0; -} diff --git a/shared/android/ipc.h b/shared/android/ipc.h deleted file mode 100644 index 0cc3f02..0000000 --- a/shared/android/ipc.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef BARE_KIT_ANDROID_IPC_H -#define BARE_KIT_ANDROID_IPC_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include - -#include "../ipc.h" - -struct bare_ipc_poll_s { - bare_ipc_t *ipc; - - ALooper *looper; - - int events; - - bare_ipc_poll_cb cb; - - void *data; -}; - -#ifdef __cplusplus -} -#endif - -#endif // BARE_KIT_ANDROID_IPC_H diff --git a/shared/android/jvm.c b/shared/android/jvm.c deleted file mode 100644 index 79b52d2..0000000 --- a/shared/android/jvm.c +++ /dev/null @@ -1,16 +0,0 @@ -#include -#include - -#include "jvm.h" - -static JavaVM *bare_kit__jvm = NULL; - -void -bare_kit__jvm_set(JavaVM *vm) { - bare_kit__jvm = vm; -} - -JavaVM * -bare_kit__jvm_get(void) { - return bare_kit__jvm; -} diff --git a/shared/android/jvm.h b/shared/android/jvm.h deleted file mode 100644 index 528627b..0000000 --- a/shared/android/jvm.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef BARE_KIT_ANDROID_JVM_H -#define BARE_KIT_ANDROID_JVM_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -void -bare_kit__jvm_set(JavaVM *vm); - -JavaVM * -bare_kit__jvm_get(void); - -#ifdef __cplusplus -} -#endif - -#endif // BARE_KIT_ANDROID_JVM_H diff --git a/shared/android/suspension.h b/shared/android/suspension.h deleted file mode 100644 index 26d06cb..0000000 --- a/shared/android/suspension.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef BARE_KIT_ANDROID_SUSPENSION_H -#define BARE_KIT_ANDROID_SUSPENSION_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "../suspension.h" - -struct bare_suspension_s {}; - -#ifdef __cplusplus -} -#endif - -#endif // BARE_KIT_ANDROID_SUSPENSION_H diff --git a/shared/apple/ipc.h b/shared/apple/ipc.h deleted file mode 100644 index 6f8dd3c..0000000 --- a/shared/apple/ipc.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef BARE_KIT_APPLE_IPC_H -#define BARE_KIT_APPLE_IPC_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -#include "../ipc.h" - -struct bare_ipc_poll_s { - bare_ipc_t *ipc; - - _Atomic int events; - - _Atomic bare_ipc_poll_cb cb; - - void *data; -}; - -#ifdef __cplusplus -} -#endif - -#endif // BARE_KIT_APPLE_IPC_H diff --git a/shared/apple/suspension.h b/shared/apple/suspension.h deleted file mode 100644 index c1336b9..0000000 --- a/shared/apple/suspension.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef BARE_KIT_APPLE_SUSPENSION_H -#define BARE_KIT_APPLE_SUSPENSION_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "../suspension.h" - -struct bare_suspension_s { -#if defined(BARE_KIT_IOS) - // Retained, as an expiration handler may outlive the suspension. - void *task; -#endif -}; - -#ifdef __cplusplus -} -#endif - -#endif // BARE_KIT_APPLE_SUSPENSION_H diff --git a/shared/context.c b/shared/context.c deleted file mode 100644 index bc1ea03..0000000 --- a/shared/context.c +++ /dev/null @@ -1,4 +0,0 @@ -#include "context.h" - -void -bare_kit__publish_context(bare_t *bare) {} diff --git a/shared/context.h b/shared/context.h deleted file mode 100644 index 78298a9..0000000 --- a/shared/context.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef BARE_KIT_CONTEXT_H -#define BARE_KIT_CONTEXT_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Publish the handles that only the embedder can produce for the addons of the - * process to retrieve with `bare_context_get()`. Must be called before the - * first `bare_load()`, as an addon only sees what was published before it was - * loaded. - */ -void -bare_kit__publish_context(bare_t *bare); - -#ifdef __cplusplus -} -#endif - -#endif // BARE_KIT_CONTEXT_H diff --git a/shared/events.c b/shared/events.c deleted file mode 100644 index 49cf513..0000000 --- a/shared/events.c +++ /dev/null @@ -1,7 +0,0 @@ -#include "events.h" - -void -bare_kit__on_thread_enter(bare_worklet_state_t *state) {} - -void -bare_kit__on_thread_exit(bare_worklet_state_t *state) {} diff --git a/shared/events.h b/shared/events.h deleted file mode 100644 index 17e137c..0000000 --- a/shared/events.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef BARE_KIT_EVENTS_H -#define BARE_KIT_EVENTS_H - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct bare_worklet_state_s bare_worklet_state_t; - -void -bare_kit__on_thread_enter(bare_worklet_state_t *state); - -void -bare_kit__on_thread_exit(bare_worklet_state_t *state); - -#ifdef __cplusplus -} -#endif - -#endif // BARE_KIT_EVENTS_H diff --git a/shared/ipc.h b/shared/ipc.h deleted file mode 100644 index 5159a58..0000000 --- a/shared/ipc.h +++ /dev/null @@ -1,130 +0,0 @@ -#ifndef BARE_KIT_IPC_H -#define BARE_KIT_IPC_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -#include "queue.h" -#include "worklet.h" - -#define BARE_IPC_READ_BUFFER_SIZE (64 * 1024) - -typedef struct bare_ipc_s bare_ipc_t; -typedef struct bare_ipc_poll_s bare_ipc_poll_t; - -typedef void (*bare_ipc_poll_cb)(bare_ipc_poll_t *, int events); - -enum { - bare_ipc_readable = 0x1, - bare_ipc_writable = 0x2, -}; - -enum { - bare_ipc_would_block = -1, - bare_ipc_error = -2, -}; - -struct bare_ipc_s { - // NULL once closed, as closing gives up the ipc's share of the queue. - bare_queue_port_t *port; - uv_mutex_t lock; - - // The rest of a message too large for the last read. - bare_queue_message_t pending; - size_t offset; - - bare_ipc_poll_t *poll; - - // Owned by the ipc rather than the poll, as the worklet signals it for as long - // as the port is open. - void *signal; -}; - -// Implemented per platform. `bare_ipc__signal` may run on the worklet thread, so -// it may only touch state owned by the ipc. -int -bare_ipc__signal_init(bare_ipc_t *ipc); - -void -bare_ipc__signal_destroy(bare_ipc_t *ipc); - -void -bare_ipc__signal(bare_ipc_t *ipc); - -// Calls the poll back with whichever of its events are ready, as a signal says -// that the queue changed but not how. Platforms call it on each wake. -void -bare_ipc__dispatch(bare_ipc_t *ipc); - -#if defined(BARE_KIT_DARWIN) || defined(BARE_KIT_IOS) -#include "apple/ipc.h" -#endif - -#if defined(BARE_KIT_ANDROID) -#include "android/ipc.h" -#endif - -// Linux and Windows have no host run loop to post to, so they run their own. -#if defined(BARE_KIT_LINUX) || defined(BARE_KIT_WINDOWS) -#include "uv/ipc.h" -#endif - -int -bare_ipc_alloc(bare_ipc_t **result); - -// Fails if the worklet already has an ipc. -int -bare_ipc_init(bare_ipc_t *ipc, bare_worklet_t *worklet); - -// Closes the host end, after which reads return EOF and writes fail. Closing -// twice is a no-op. -void -bare_ipc_close(bare_ipc_t *ipc); - -// May be called before or after `bare_worklet_destroy`, and from a poll callback -// of the ipc itself. -void -bare_ipc_destroy(bare_ipc_t *ipc); - -// Reads up to `len` bytes, which must not be 0, into the caller's `data`. -// Returns the number of bytes read, 0 at EOF, or `bare_ipc_would_block`. -int -bare_ipc_read(bare_ipc_t *ipc, void *data, size_t len); - -int -bare_ipc_write(bare_ipc_t *ipc, const void *data, size_t len); - -// On Android, a poll must be started, stopped and destroyed on the thread that -// initialized it, whose looper runs its callback. -int -bare_ipc_poll_alloc(bare_ipc_poll_t **result); - -int -bare_ipc_poll_init(bare_ipc_poll_t *poll, bare_ipc_t *ipc); - -void -bare_ipc_poll_destroy(bare_ipc_poll_t *poll); - -void * -bare_ipc_poll_get_data(bare_ipc_poll_t *poll); - -void -bare_ipc_poll_set_data(bare_ipc_poll_t *poll, void *data); - -bare_ipc_t * -bare_ipc_poll_get_ipc(bare_ipc_poll_t *poll); - -int -bare_ipc_poll_start(bare_ipc_poll_t *poll, int events, bare_ipc_poll_cb cb); - -int -bare_ipc_poll_stop(bare_ipc_poll_t *poll); - -#ifdef __cplusplus -} -#endif - -#endif // BARE_KIT_IPC_H diff --git a/shared/linux/suspension.c b/shared/linux/suspension.c deleted file mode 100644 index 4f6b6b8..0000000 --- a/shared/linux/suspension.c +++ /dev/null @@ -1,19 +0,0 @@ -#include "../suspension.h" - -int -bare_suspension_init(bare_suspension_t *suspension) { - return 0; -} - -int -bare_suspension_start(bare_suspension_t *result, int timeout) { - return timeout < 0 ? 30000 : timeout; -} - -int -bare_suspension_end(bare_suspension_t *suspension) { - return 0; -} - -void -bare_suspension_destroy(bare_suspension_t *suspension) {} diff --git a/shared/linux/suspension.h b/shared/linux/suspension.h deleted file mode 100644 index 93849c8..0000000 --- a/shared/linux/suspension.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef BARE_KIT_LINUX_SUSPENSION_H -#define BARE_KIT_LINUX_SUSPENSION_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "../suspension.h" - -struct bare_suspension_s {}; - -#ifdef __cplusplus -} -#endif - -#endif // BARE_KIT_LINUX_SUSPENSION_H diff --git a/shared/uv/ipc.h b/shared/uv/ipc.h deleted file mode 100644 index 1ede71d..0000000 --- a/shared/uv/ipc.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef BARE_KIT_UV_IPC_H -#define BARE_KIT_UV_IPC_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "../ipc.h" - -struct bare_ipc_poll_s { - bare_ipc_t *ipc; - - int events; - - bare_ipc_poll_cb cb; - - void *data; -}; - -#ifdef __cplusplus -} -#endif - -#endif // BARE_KIT_UV_IPC_H diff --git a/shared/win32/suspension.c b/shared/win32/suspension.c deleted file mode 100644 index 4f6b6b8..0000000 --- a/shared/win32/suspension.c +++ /dev/null @@ -1,19 +0,0 @@ -#include "../suspension.h" - -int -bare_suspension_init(bare_suspension_t *suspension) { - return 0; -} - -int -bare_suspension_start(bare_suspension_t *result, int timeout) { - return timeout < 0 ? 30000 : timeout; -} - -int -bare_suspension_end(bare_suspension_t *suspension) { - return 0; -} - -void -bare_suspension_destroy(bare_suspension_t *suspension) {} diff --git a/shared/win32/suspension.h b/shared/win32/suspension.h deleted file mode 100644 index 881c7fe..0000000 --- a/shared/win32/suspension.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifndef BARE_KIT_WINDOWS_SUSPENSION_H -#define BARE_KIT_WINDOWS_SUSPENSION_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "../suspension.h" - -struct bare_suspension_s {}; - -#ifdef __cplusplus -} -#endif - -#endif // BARE_KIT_WINDOWS_SUSPENSION_H diff --git a/shared/worklet.h b/shared/worklet.h deleted file mode 100644 index 1a8d0f8..0000000 --- a/shared/worklet.h +++ /dev/null @@ -1,161 +0,0 @@ -#ifndef BARE_KIT_WORKLET_H -#define BARE_KIT_WORKLET_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include -#include -#include - -#include "queue.h" -#include "suspension.h" - -typedef struct bare_worklet_s bare_worklet_t; -typedef struct bare_worklet_options_s bare_worklet_options_t; -typedef struct bare_worklet_state_s bare_worklet_state_t; -typedef struct bare_worklet_push_s bare_worklet_push_t; - -typedef void (*bare_worklet_push_cb)(bare_worklet_push_t *, const char *error, const uv_buf_t *reply); - -struct bare_worklet_options_s { - /** - * The memory limit of each JavaScript heap. By default, the limit will be - * inferred based on the amount of physical memory of the device. - * - * Note that the limit applies individually to each thread, including the - * main thread. - */ - size_t memory_limit; - - /** - * The directory in which assets should be stored. The worklet require both - * read and write access to the directory. By default, assets may not be - * referenced and doing so will result in a runtime error. - */ - const char *assets; -}; - -struct bare_worklet_s { - bare_t *bare; - - bare_worklet_options_t options; - - bare_worklet_state_t *state; - - const char *filename; - - struct { - enum { - bare_worklet_source_none = 0, - bare_worklet_source_buffer = 1, - } type; - - union { - uv_buf_t buffer; - }; - } source; - - void *finalize_hint; - - int argc; - const char **argv; - - uv_thread_t thread; - uv_barrier_t ready; - uv_sem_t *finished; - - bare_queue_t *queue; - - js_threadsafe_function_t *push; - - void *data; -}; - -struct bare_worklet_push_s { - bare_worklet_t *worklet; - - bare_worklet_push_cb cb; - - uv_buf_t payload; - - void *data; - - // Private: the worklet's list of pending pushes. - bare_worklet_push_t *previous; - bare_worklet_push_t *next; -}; - -/** - * Enable trade-off of performance for memory. Must be configured before - * starting the first worklet. - */ -int -bare_worklet_optimize_for_memory(bool enabled); - -int -bare_worklet_alloc(bare_worklet_t **result); - -int -bare_worklet_init(bare_worklet_t *worklet, const bare_worklet_options_t *options); - -// Terminates the worklet if it is still running and hands it over to tear -// itself down, without blocking. -void -bare_worklet_destroy(bare_worklet_t *worklet); - -int -bare_worklet_on_suspend(bare_worklet_t *worklet, bare_suspend_cb cb, void *data); - -int -bare_worklet_on_wakeup(bare_worklet_t *worklet, bare_wakeup_cb cb, void *data); - -int -bare_worklet_on_idle(bare_worklet_t *worklet, bare_idle_cb cb, void *data); - -int -bare_worklet_on_resume(bare_worklet_t *worklet, bare_resume_cb cb, void *data); - -void * -bare_worklet_get_data(bare_worklet_t *worklet); - -void -bare_worklet_set_data(bare_worklet_t *worklet, void *data); - -int -bare_worklet_start(bare_worklet_t *worklet, const char *filename, const uv_buf_t *source, int argc, const char *argv[]); - -// Suspending, resuming, waking up or terminating a worklet that has not started -// is a no-op. -int -bare_worklet_suspend(bare_worklet_t *worklet, int linger); - -int -bare_worklet_resume(bare_worklet_t *worklet); - -int -bare_worklet_wakeup(bare_worklet_t *worklet, int deadline); - -int -bare_worklet_terminate(bare_worklet_t *worklet); - -// Fails if the worklet has not started or its loop has stopped, in which case -// `cb` is not called. Otherwise `cb` is called exactly once on the worklet -// thread, with the reply or with an error if the worklet stops first, and `req` -// must be kept until then. -int -bare_worklet_push(bare_worklet_t *worklet, bare_worklet_push_t *req, const uv_buf_t *payload, bare_worklet_push_cb cb); - -void * -bare_worklet_push_get_data(bare_worklet_push_t *req); - -void -bare_worklet_push_set_data(bare_worklet_push_t *req, void *data); - -#ifdef __cplusplus -} -#endif - -#endif // BARE_KIT_WORKLET_H diff --git a/shared/worklet.js b/shared/worklet.js deleted file mode 100644 index 426a1e0..0000000 --- a/shared/worklet.js +++ /dev/null @@ -1,216 +0,0 @@ -const path = require('bare-path') -const fs = require('bare-fs') -const crypto = require('bare-crypto') -const { fileURLToPath, pathToFileURL } = require('bare-url') -const EventEmitter = require('bare-events') -const URL = require('bare-url') -const Bundle = require('bare-bundle') -const Module = require('bare-module') -const { startsWithWindowsDriveLetter } = require('bare-module-resolve') -const SystemLog = require('bare-system-logger') -const Console = require('bare-console') -const { Duplex } = require('bare-stream') -const unpack = require('bare-unpack') - -const { protocol } = module - -global.console = new Console(new SystemLog()) - -const errors = { - IPC_CLOSED() { - const err = new Error('IPC stream closed') - err.code = 'IPC_CLOSED' - return err - } -} - -// A signal from the queue means re-check both reads and a pending write. -class IPCStream extends Duplex { - constructor(native) { - super() - - this._native = native - this._reading = false - this._pendingWrite = null - } - - _read() { - this._reading = true - this._drain() - } - - _drain() { - if (!this._reading) return - - let chunk - while ((chunk = this._native.read()) !== undefined) { - if (chunk === null) { - this._reading = false - this.push(null) - return - } - - if (this.push(Buffer.from(chunk)) === false) { - this._reading = false - return - } - } - } - - _write(chunk, encoding, cb) { - this._send(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding), cb) - } - - _send(chunk, cb) { - const n = this._native.write(chunk) - - if (n === null) cb(errors.IPC_CLOSED()) - else if (n < 0) this._pendingWrite = { chunk, cb } - else if (n < chunk.byteLength) this._pendingWrite = { chunk: chunk.subarray(n), cb } - else cb(null) - } - - _retry() { - if (this._pendingWrite === null) return - - const { chunk, cb } = this._pendingWrite - this._pendingWrite = null - - this._send(chunk, cb) - } - - // A half-close: the host reads EOF but may keep writing. streamx only calls - // _final once pending writes have drained. - _final(cb) { - this._native.end() - cb(null) - } - - _onsignal() { - this._retry() - this._drain() - } - - ref() { - this._native.ref() - return this - } - - unref() { - this._native.unref() - return this - } -} - -class BareKit extends EventEmitter { - constructor() { - super() - - this.IPC = null - } - - [Symbol.for('bare.inspect')]() { - return { - __proto__: { constructor: BareKit } - } - } -} - -exports.BareKit = new BareKit() - -Object.defineProperty(global, 'BareKit', { - value: exports.BareKit, - enumerable: true, - writable: false, - configurable: true -}) - -// Returns the callback the worklet loop invokes when the queue signals. -exports.openIPC = function openIPC(native) { - const ipc = new IPCStream(native) - - Bare.IPC = exports.BareKit.IPC = ipc - - Bare.on('suspend', () => ipc.unref()).on('resume', () => ipc.ref()) - - return () => ipc._onsignal() -} - -exports.push = function push(payload, reply) { - if (exports.BareKit.emit('push', Buffer.from(payload), replyOnce) === false) { - replyOnce(null, null) - } - - function replyOnce(err, payload, encoding) { - if (err) { - reply(String(err), null) - } else { - reply(null, typeof payload === 'string' ? Buffer.from(payload, encoding) : payload) - } - - reply = noop - } -} - -exports.start = async function start(filename, source, assets) { - if (assets !== null) { - let url - - if (startsWithWindowsDriveLetter(assets)) { - url = null - } else { - url = URL.parse(assets) - } - - if (url === null) url = pathToFileURL(assets) - - assets = fileURLToPath(url) - } - - let url - - if (startsWithWindowsDriveLetter(filename)) { - url = null - } else { - url = URL.parse(filename) - } - - if (url === null) url = pathToFileURL(filename) - - if (source === null) source = protocol.readSync(url) - else source = Buffer.from(source) - - if (assets !== null && path.extname(url.href) === '.bundle') { - const bundle = Bundle.from(source) - - if (bundle.id !== null && bundle.assets.length > 0) { - const id = crypto.createHash('blake2b256').update(bundle.id).digest('hex') - - const root = path.join(assets, id) - - const tmp = fs.existsSync(root) ? null : path.join(assets, 'tmp') - - if (tmp !== null) { - fs.rmSync(tmp, { recursive: true, force: true }) - fs.mkdirSync(tmp, { recursive: true }) - } - - source = await unpack(bundle, { files: false, assets: true }, (key) => { - if (tmp !== null) { - const target = path.join(tmp, key) - - fs.mkdirSync(path.dirname(target), { recursive: true }) - fs.writeFileSync(target, bundle.read(key)) - } - - return pathToFileURL(path.join(root, key)).href - }) - - if (tmp !== null) fs.renameSync(tmp, root) - } - } - - return Module.loadSync(url, source, { protocol }) -} - -function noop() {} diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..16b22a3 --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,225 @@ +add_bare_bundle( + bare_kit_bundle + ENTRY src/worklet.js + OUT src/worklet.bundle.h + BUILTINS src/builtins.json + WORKING_DIRECTORY .. +) + +add_library(bare_kit OBJECT) + +set_target_properties( + bare_kit + PROPERTIES + C_STANDARD 11 + POSITION_INDEPENDENT_CODE ON +) + +target_sources( + bare_kit + INTERFACE + ../include/bare-kit.h + PRIVATE + ipc.h + ipc.c + platform.h + queue.h + queue.c + resources.h + suspension.h + symbols.h + worklet.c + worklet.bundle.h + worklet.h +) + +target_include_directories( + bare_kit + PUBLIC + ../include + $ +) + +if(APPLE) + target_sources( + bare_kit + PRIVATE + apple/ipc.m + apple/resources.c + ) + + target_link_libraries( + bare_kit + PUBLIC + "-framework CoreFoundation" + ) +else() + target_sources( + bare_kit + PRIVATE + standalone/ipc.c + ) +endif() + +if(ANDROID) + target_sources( + bare_kit + PRIVATE + android/jvm.h + android/platform.c + android/resources.c + ) + + target_link_libraries( + bare_kit + PUBLIC + android + ) +else() + target_sources( + bare_kit + PRIVATE + platform.c + ) +endif() + +if(NOT APPLE AND NOT ANDROID) + target_sources( + bare_kit + PRIVATE + resources.c + ) +endif() + +if(IOS) + target_sources( + bare_kit + PRIVATE + ios/suspension.m + ) + + target_link_libraries( + bare_kit + PUBLIC + "-framework UIKit" + ) + + target_compile_definitions( + bare_kit + PRIVATE + BARE_KIT_IOS + ) +else() + target_sources( + bare_kit + PRIVATE + suspension.c + ) +endif() + +target_link_libraries( + bare_kit + INTERFACE + $ + PUBLIC + rlimit_static +) + +if(LINUX) + target_sources( + bare_kit + PRIVATE + linux/symbols.c + ) + + target_link_libraries( + bare_kit + PUBLIC + ${CMAKE_DL_LIBS} + ) +else() + target_sources( + bare_kit + PRIVATE + symbols.c + ) +endif() + +link_bare_modules(bare_kit WORKING_DIRECTORY ..) + +add_library(bare_kit_shared SHARED) + +set_target_properties( + bare_kit_shared + PROPERTIES + OUTPUT_NAME bare-kit +) + +if(WIN32) + target_sources( + bare_kit_shared + PUBLIC + win32/bare-kit.def + ) +endif() + +target_include_directories( + bare_kit_shared + INTERFACE + $ +) + +target_link_libraries( + bare_kit_shared + PRIVATE + bare_kit +) + +if(ANDROID) + target_link_options( + bare_kit_shared + PRIVATE + "-Wl,-z,global" # Resolve addons against the library when loaded locally + ) +endif() + +if(LINUX) + target_link_options( + bare_kit_shared + PUBLIC + "-Wl,-z,now" # Use eager binding + ) +endif() + +add_library(bare_kit_static STATIC) + +set_target_properties( + bare_kit_static + PROPERTIES + OUTPUT_NAME bare-kit + PREFIX lib +) + +if(WIN32) + target_sources( + bare_kit_static + PUBLIC + win32/bare-kit.def + ) +endif() + +target_include_directories( + bare_kit_static + INTERFACE + $ +) + +target_link_libraries( + bare_kit_static + PRIVATE + bare_kit +) + +install(TARGETS bare_kit_shared bare_kit_static) + +install(FILES ../include/bare-kit.h DESTINATION include) diff --git a/src/android/jvm.h b/src/android/jvm.h new file mode 100644 index 0000000..1bda223 --- /dev/null +++ b/src/android/jvm.h @@ -0,0 +1,12 @@ +#ifndef BARE_KIT_ANDROID_JVM_H +#define BARE_KIT_ANDROID_JVM_H + +#include + +/** + * The environment of the calling thread, which must be attached to the JVM. + */ +JNIEnv * +bare_kit__get_env(void); + +#endif // BARE_KIT_ANDROID_JVM_H diff --git a/src/android/platform.c b/src/android/platform.c new file mode 100644 index 0000000..cc4db19 --- /dev/null +++ b/src/android/platform.c @@ -0,0 +1,197 @@ +#include +#include +#include +#include + +#include "../platform.h" +#include "jvm.h" + +static JavaVM *_Atomic bare_kit__jvm = NULL; + +JNIEXPORT jint JNICALL +JNI_OnLoad(JavaVM *vm, void *reserved) { + bare_kit__jvm = vm; + + return JNI_VERSION_1_6; +} + +static void +bare_kit__set_context_class_loader(JNIEnv *env) { + jclass thread_class = (*env)->FindClass(env, "java/lang/Thread"); + assert(thread_class != NULL); + + jmethodID current_thread = (*env)->GetStaticMethodID(env, thread_class, "currentThread", "()Ljava/lang/Thread;"); + assert(current_thread != NULL); + + jobject thread = (*env)->CallStaticObjectMethod(env, thread_class, current_thread); + assert(thread != NULL); + assert(!(*env)->ExceptionCheck(env)); + + jclass activity_thread_class = (*env)->FindClass(env, "android/app/ActivityThread"); + assert(activity_thread_class != NULL); + + jmethodID current_application = (*env)->GetStaticMethodID(env, activity_thread_class, "currentApplication", "()Landroid/app/Application;"); + assert(current_application != NULL); + + jobject application = (*env)->CallStaticObjectMethod(env, activity_thread_class, current_application); + assert(application != NULL); + assert(!(*env)->ExceptionCheck(env)); + + jclass application_class = (*env)->GetObjectClass(env, application); + assert(application_class != NULL); + + jmethodID get_class_loader = (*env)->GetMethodID(env, application_class, "getClassLoader", "()Ljava/lang/ClassLoader;"); + assert(get_class_loader != NULL); + + jobject class_loader = (*env)->CallObjectMethod(env, application, get_class_loader); + assert(class_loader != NULL); + assert(!(*env)->ExceptionCheck(env)); + + jmethodID set_context_class_loader = (*env)->GetMethodID(env, thread_class, "setContextClassLoader", "(Ljava/lang/ClassLoader;)V"); + assert(set_context_class_loader != NULL); + + (*env)->CallVoidMethod(env, thread, set_context_class_loader, class_loader); + assert(!(*env)->ExceptionCheck(env)); + + (*env)->DeleteLocalRef(env, class_loader); + (*env)->DeleteLocalRef(env, application_class); + (*env)->DeleteLocalRef(env, application); + (*env)->DeleteLocalRef(env, activity_thread_class); + (*env)->DeleteLocalRef(env, thread); + (*env)->DeleteLocalRef(env, thread_class); +} + +void +bare_kit__on_thread_enter(void) { + int err; + + JavaVM *vm = bare_kit__jvm; + assert(vm != NULL); + + JNIEnv *env; + err = (*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6); + assert(err == JNI_EDETACHED); + + JavaVMAttachArgs args = { + JNI_VERSION_1_6, + "bare-worklet", + NULL, + }; + + err = (*vm)->AttachCurrentThread(vm, &env, &args); + assert(err == JNI_OK); + + bare_kit__set_context_class_loader(env); +} + +void +bare_kit__on_thread_exit(void) { + int err; + + JavaVM *vm = bare_kit__jvm; + assert(vm != NULL); + + JNIEnv *env; + err = (*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6); + assert(err == JNI_OK); + + err = (*vm)->DetachCurrentThread(vm); + assert(err == JNI_OK); +} + +// There is only one JVM per process, so a JVM given by the options replaces the +// one from `JNI_OnLoad()` for the process. +void +bare_kit__retain_context(bare_worklet_options_t *result, const bare_worklet_options_t *options) { + int err; + + if (options->platform.android.jvm) bare_kit__jvm = options->platform.android.jvm; + + if (options->platform.android.context == NULL) return; + + JavaVM *vm = bare_kit__jvm; + assert(vm != NULL); + + JNIEnv *env; + err = (*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6); + assert(err == JNI_OK); + + result->platform.android.context = (*env)->NewGlobalRef(env, (jobject) options->platform.android.context); +} + +// The worklet may be destroyed from a thread that isn't attached to the JVM, +// in which case the thread is attached for the duration of the call. +void +bare_kit__release_context(const bare_worklet_options_t *options) { + int err; + + if (options->platform.android.context == NULL) return; + + JavaVM *vm = bare_kit__jvm; + assert(vm != NULL); + + JNIEnv *env; + err = (*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6); + + bool attached = err == JNI_EDETACHED; + + if (attached) { + err = (*vm)->AttachCurrentThread(vm, &env, NULL); + } + + assert(err == JNI_OK); + + (*env)->DeleteGlobalRef(env, (jobject) options->platform.android.context); + + if (attached) { + err = (*vm)->DetachCurrentThread(vm); + assert(err == JNI_OK); + } +} + +static void +bare_kit__on_context_destroy(const char *key, void *value) { + int err; + + JavaVM *vm = bare_kit__jvm; + + JNIEnv *env; + err = (*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6); + assert(err == JNI_OK); + + (*env)->DeleteGlobalRef(env, (jobject) value); +} + +void +bare_kit__publish_context(bare_t *bare, const bare_worklet_options_t *options) { + int err; + + JavaVM *vm = bare_kit__jvm; + assert(vm != NULL); + + err = bare_context_set(bare, "bare.android.jvm.v1", vm, NULL); + assert(err == 0); + + if (options->platform.android.context) { + JNIEnv *env; + err = (*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6); + assert(err == JNI_OK); + + err = bare_context_set(bare, "bare.android.context.v1", (*env)->NewGlobalRef(env, (jobject) options->platform.android.context), bare_kit__on_context_destroy); + assert(err == 0); + } +} + +JNIEnv * +bare_kit__get_env(void) { + int err; + + JavaVM *vm = bare_kit__jvm; + assert(vm != NULL); + + JNIEnv *env; + err = (*vm)->GetEnv(vm, (void **) &env, JNI_VERSION_1_6); + assert(err == JNI_OK); + + return env; +} diff --git a/src/android/resources.c b/src/android/resources.c new file mode 100644 index 0000000..88244e5 --- /dev/null +++ b/src/android/resources.c @@ -0,0 +1,145 @@ +#include +#include +#include +#include +#include +#include + +#include "../resources.h" +#include "jvm.h" + +typedef struct { + jobject assets; + AAssetManager *manager; +} bare_kit__resources_t; + +static js_value_t * +bare_kit__on_read_resource(js_env_t *env, js_callback_info_t *info) { + int err; + + size_t argc = 1; + js_value_t *argv[1]; + + bare_kit__resources_t *resources; + err = js_get_callback_info(env, info, &argc, argv, NULL, (void **) &resources); + assert(err == 0); + + assert(argc == 1); + + size_t len; + err = js_get_value_string_utf8(env, argv[0], NULL, 0, &len); + assert(err == 0); + + utf8_t *name = malloc(len + 1); + err = js_get_value_string_utf8(env, argv[0], name, len + 1, NULL); + assert(err == 0); + + AAsset *asset = AAssetManager_open(resources->manager, (const char *) name, AASSET_MODE_STREAMING); + + free(name); + + js_value_t *result; + + if (asset == NULL) { + err = js_get_null(env, &result); + assert(err == 0); + + return result; + } + + size_t length = AAsset_getLength64(asset); + + char *data; + err = js_create_arraybuffer(env, length, (void **) &data, &result); + assert(err == 0); + + for (size_t read = 0; read < length;) { + int n = AAsset_read(asset, data + read, length - read); + assert(n > 0); + + read += n; + } + + AAsset_close(asset); + + return result; +} + +static void +bare_kit__on_resources_finalize(js_env_t *env, void *data, void *finalize_hint) { + bare_kit__resources_t *resources = data; + + JNIEnv *jni = bare_kit__get_env(); + + (*jni)->DeleteGlobalRef(jni, resources->assets); + + free(resources); +} + +// The code cache directory is cleared when the application is updated, so +// extracted resources never go stale. +void +bare_kit__create_resources(js_env_t *env, const bare_worklet_options_t *options, js_value_t **directory, js_value_t **read) { + int err; + + err = js_get_null(env, directory); + assert(err == 0); + + err = js_get_null(env, read); + assert(err == 0); + + jobject context = (jobject) options->platform.android.context; + + if (context == NULL) return; + + JNIEnv *jni = bare_kit__get_env(); + + jclass context_class = (*jni)->GetObjectClass(jni, context); + + jmethodID get_code_cache_dir = (*jni)->GetMethodID(jni, context_class, "getCodeCacheDir", "()Ljava/io/File;"); + assert(get_code_cache_dir != NULL); + + jmethodID get_assets = (*jni)->GetMethodID(jni, context_class, "getAssets", "()Landroid/content/res/AssetManager;"); + assert(get_assets != NULL); + + jobject dir = (*jni)->CallObjectMethod(jni, context, get_code_cache_dir); + assert(dir != NULL); + assert(!(*jni)->ExceptionCheck(jni)); + + jclass file_class = (*jni)->GetObjectClass(jni, dir); + + jmethodID get_path = (*jni)->GetMethodID(jni, file_class, "getPath", "()Ljava/lang/String;"); + assert(get_path != NULL); + + jstring path = (*jni)->CallObjectMethod(jni, dir, get_path); + assert(path != NULL); + assert(!(*jni)->ExceptionCheck(jni)); + + const char *chars = (*jni)->GetStringUTFChars(jni, path, NULL); + + err = js_create_string_utf8(env, (const utf8_t *) chars, -1, directory); + assert(err == 0); + + (*jni)->ReleaseStringUTFChars(jni, path, chars); + + jobject assets = (*jni)->CallObjectMethod(jni, context, get_assets); + assert(assets != NULL); + assert(!(*jni)->ExceptionCheck(jni)); + + bare_kit__resources_t *resources = malloc(sizeof(bare_kit__resources_t)); + + resources->assets = (*jni)->NewGlobalRef(jni, assets); + resources->manager = AAssetManager_fromJava(jni, resources->assets); + + err = js_create_function(env, "readResource", -1, bare_kit__on_read_resource, resources, read); + assert(err == 0); + + err = js_add_finalizer(env, *read, resources, bare_kit__on_resources_finalize, NULL, NULL); + assert(err == 0); + + (*jni)->DeleteLocalRef(jni, assets); + (*jni)->DeleteLocalRef(jni, path); + (*jni)->DeleteLocalRef(jni, file_class); + (*jni)->DeleteLocalRef(jni, dir); + (*jni)->DeleteLocalRef(jni, context_class); +} diff --git a/shared/apple/ipc.m b/src/apple/ipc.m similarity index 50% rename from shared/apple/ipc.m rename to src/apple/ipc.m index 1e90b0d..49c8392 100644 --- a/shared/apple/ipc.m +++ b/src/apple/ipc.m @@ -1,8 +1,7 @@ -#import #import #import -#import "ipc.h" +#import "../ipc.h" static const void *const bare_ipc_signal_queue = &bare_ipc_signal_queue; @@ -11,14 +10,6 @@ dispatch_source_t source; } bare_ipc_signal_t; -// Runs the block in order with the handlers, waiting for any running handler to -// finish first, unless called from that handler. -static void -bare_ipc__sync(bare_ipc_signal_t *signal, dispatch_block_t block) { - if (dispatch_get_specific(bare_ipc_signal_queue) == signal) block(); - else dispatch_sync(signal->queue, block); -} - int bare_ipc__signal_init(bare_ipc_t *ipc) { bare_ipc_signal_t *signal = malloc(sizeof(bare_ipc_signal_t)); @@ -31,10 +22,6 @@ dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_OR, 0, 0, queue); - dispatch_source_set_cancel_handler(source, ^{ - dispatch_release(source); - }); - dispatch_source_set_event_handler(source, ^{ @autoreleasepool { bare_ipc__dispatch(ipc); @@ -62,65 +49,44 @@ bare_ipc__signal_destroy(bare_ipc_t *ipc) { bare_ipc_signal_t *signal = (bare_ipc_signal_t *) ipc->signal; - dispatch_source_cancel(signal->source); + dispatch_source_t source = signal->source; - bare_ipc__sync(signal, ^{}); + if (dispatch_get_specific(bare_ipc_signal_queue) == signal) { + // A handler cannot wait for the cancellation it is itself part of. + dispatch_source_cancel(source); + } else { + // Waited for, so that the handlers are released along with the source + // rather than at some later point. + dispatch_semaphore_t cancelled = dispatch_semaphore_create(0); - dispatch_release(signal->queue); + dispatch_source_set_cancel_handler(source, ^{ + dispatch_semaphore_signal(cancelled); + }); - free(signal); + dispatch_source_cancel(source); - ipc->signal = NULL; -} + dispatch_semaphore_wait(cancelled, DISPATCH_TIME_FOREVER); -int -bare_ipc_poll_init(bare_ipc_poll_t *poll, bare_ipc_t *ipc) { - poll->ipc = ipc; - poll->data = NULL; - - atomic_init(&poll->events, 0); - atomic_init(&poll->cb, NULL); - - bare_ipc__sync((bare_ipc_signal_t *) ipc->signal, ^{ - ipc->poll = poll; - }); + dispatch_release(cancelled); + } - return 0; -} - -void -bare_ipc_poll_destroy(bare_ipc_poll_t *poll) { - int err; - err = bare_ipc_poll_stop(poll); - assert(err == 0); + dispatch_release(source); - bare_ipc_t *ipc = poll->ipc; - - // So the caller may free the poll once this returns. - bare_ipc__sync((bare_ipc_signal_t *) ipc->signal, ^{ - ipc->poll = NULL; - }); -} - -int -bare_ipc_poll_start(bare_ipc_poll_t *poll, int events, bare_ipc_poll_cb cb) { - if (events == 0) return bare_ipc_poll_stop(poll); - - poll->events = events; - - atomic_store(&poll->cb, cb); + dispatch_release(signal->queue); - // Level-triggered: signal once in case the events are already ready. - bare_ipc__signal(poll->ipc); + free(signal); - return 0; + ipc->signal = NULL; } -int -bare_ipc_poll_stop(bare_ipc_poll_t *poll) { - poll->events = 0; +void +bare_ipc__set_poll(bare_ipc_t *ipc, bare_ipc_poll_t *poll) { + bare_ipc_signal_t *signal = (bare_ipc_signal_t *) ipc->signal; - atomic_store(&poll->cb, NULL); + dispatch_block_t block = ^{ + ipc->poll = poll; + }; - return 0; + if (dispatch_get_specific(bare_ipc_signal_queue) == signal) block(); + else dispatch_sync(signal->queue, block); } diff --git a/src/apple/resources.c b/src/apple/resources.c new file mode 100644 index 0000000..51bc91c --- /dev/null +++ b/src/apple/resources.c @@ -0,0 +1,95 @@ +#include +#include +#include +#include +#include + +#include "../resources.h" + +static bool +bare_kit__has_extension(CFURLRef url, CFStringRef extension) { + CFStringRef actual = CFURLCopyPathExtension(url); + + if (actual == NULL) return false; + + bool equal = CFStringCompare(actual, extension, 0) == kCFCompareEqualTo; + + CFRelease(actual); + + return equal; +} + +// An application extension is embedded in the bundle of its application, whose +// resources it shares. An executable outside of a bundle has no resources. +static CFURLRef +bare_kit__copy_application_url(void) { + CFBundleRef main = CFBundleGetMainBundle(); + + if (main == NULL) return NULL; + + CFURLRef url = CFBundleCopyBundleURL(main); + + if (url == NULL) return NULL; + + if (bare_kit__has_extension(url, CFSTR("appex"))) { + while (!bare_kit__has_extension(url, CFSTR("app"))) { + CFURLRef parent = CFURLCreateCopyDeletingLastPathComponent(NULL, url); + + bool root = CFEqual(parent, url); + + CFRelease(url); + + url = parent; + + if (root) break; + } + } + + if (bare_kit__has_extension(url, CFSTR("app"))) return url; + + CFRelease(url); + + return NULL; +} + +void +bare_kit__create_resources(js_env_t *env, const bare_worklet_options_t *options, js_value_t **directory, js_value_t **read) { + int err; + + err = js_get_null(env, directory); + assert(err == 0); + + err = js_get_null(env, read); + assert(err == 0); + + CFURLRef url = bare_kit__copy_application_url(); + + if (url == NULL) return; + + CFBundleRef bundle = CFBundleCreate(NULL, url); + + CFRelease(url); + + if (bundle == NULL) return; + + CFURLRef resources = CFBundleCopyResourcesDirectoryURL(bundle); + + CFRelease(bundle); + + if (resources == NULL) return; + + CFURLRef absolute = CFURLCopyAbsoluteURL(resources); + + CFRelease(resources); + + char path[PATH_MAX]; + + bool ok = CFURLGetFileSystemRepresentation(absolute, true, (UInt8 *) path, PATH_MAX); + + CFRelease(absolute); + + if (!ok) return; + + err = js_create_string_utf8(env, (const utf8_t *) path, -1, directory); + assert(err == 0); +} diff --git a/shared/builtins.json b/src/builtins.json similarity index 79% rename from shared/builtins.json rename to src/builtins.json index 60278f2..da81b5d 100644 --- a/shared/builtins.json +++ b/src/builtins.json @@ -1,4 +1,5 @@ [ + { "addon": "bare-buffer" }, { "addon": "bare-crypto" }, { "addon": "bare-fs" }, { "addon": "bare-hrtime" }, @@ -6,9 +7,11 @@ { "addon": "bare-logger" }, { "addon": "bare-module" }, { "addon": "bare-module-lexer" }, - { "addon": "bare-path" }, { "addon": "bare-os" }, + { "addon": "bare-path" }, + { "addon": "bare-structured-clone" }, { "addon": "bare-system-logger" }, + { "addon": "bare-timers" }, { "addon": "bare-type" }, { "addon": "bare-type-stripper" }, { "addon": "bare-url" } diff --git a/shared/apple/suspension.m b/src/ios/suspension.m similarity index 82% rename from shared/apple/suspension.m rename to src/ios/suspension.m index 7f19bf1..1151428 100644 --- a/shared/apple/suspension.m +++ b/src/ios/suspension.m @@ -1,11 +1,8 @@ -#if defined(BARE_KIT_IOS) -#include -#include -#endif +#import +#import -#import "suspension.h" +#import "../suspension.h" -#if defined(BARE_KIT_IOS) @interface BareSuspensionTask : NSObject { @public _Atomic UIBackgroundTaskIdentifier identifier; @@ -14,24 +11,20 @@ @interface BareSuspensionTask : NSObject { @implementation BareSuspensionTask @end -#endif int bare_suspension_init(bare_suspension_t *suspension) { -#if defined(BARE_KIT_IOS) BareSuspensionTask *task = [[BareSuspensionTask alloc] init]; atomic_init(&task->identifier, UIBackgroundTaskInvalid); suspension->task = task; -#endif return 0; } int bare_suspension_start(bare_suspension_t *suspension, int timeout) { -#if defined(BARE_KIT_IOS) UIApplication *app = [UIApplication sharedApplication]; if (app == nil) return timeout < 0 ? 30000 : timeout; @@ -51,7 +44,7 @@ @implementation BareSuspensionTask if (prev != UIBackgroundTaskInvalid) [app endBackgroundTask:prev]; - NSTimeInterval remaining = UIApplication.sharedApplication.backgroundTimeRemaining; + NSTimeInterval remaining = app.backgroundTimeRemaining; if (remaining == DBL_MAX) remaining = 30.0; @@ -60,14 +53,10 @@ @implementation BareSuspensionTask if (timeout < 0 || timeout > remaining) return remaining; return timeout; -#else - return timeout < 0 ? 30000 : timeout; -#endif } int bare_suspension_end(bare_suspension_t *suspension) { -#if defined(BARE_KIT_IOS) UIApplication *app = [UIApplication sharedApplication]; if (app == nil) return 0; @@ -79,14 +68,9 @@ @implementation BareSuspensionTask if (prev != UIBackgroundTaskInvalid) [app endBackgroundTask:prev]; return 0; -#else - return 0; -#endif } void bare_suspension_destroy(bare_suspension_t *suspension) { -#if defined(BARE_KIT_IOS) [(BareSuspensionTask *) suspension->task release]; -#endif } diff --git a/shared/ipc.c b/src/ipc.c similarity index 72% rename from shared/ipc.c rename to src/ipc.c index 6de5804..301257e 100644 --- a/shared/ipc.c +++ b/src/ipc.c @@ -11,18 +11,11 @@ bare_ipc__on_signal(bare_queue_port_t *port) { } int -bare_ipc_alloc(bare_ipc_t **result) { +bare_ipc_create(bare_worklet_t *worklet, bare_ipc_t **result) { bare_ipc_t *ipc = malloc(sizeof(bare_ipc_t)); if (ipc == NULL) return -1; - *result = ipc; - - return 0; -} - -int -bare_ipc_init(bare_ipc_t *ipc, bare_worklet_t *worklet) { ipc->pending.base = NULL; ipc->offset = 0; ipc->poll = NULL; @@ -30,19 +23,27 @@ bare_ipc_init(bare_ipc_t *ipc, bare_worklet_t *worklet) { int err = bare_ipc__signal_init(ipc); - if (err < 0) return err; + if (err < 0) { + free(ipc); + + return err; + } ipc->port = bare_queue_open_thread(worklet->queue, bare_ipc__on_signal, ipc); if (ipc->port == NULL) { bare_ipc__signal_destroy(ipc); + free(ipc); + return -1; } err = uv_mutex_init(&ipc->lock); assert(err == 0); + *result = ipc; + return 0; } @@ -65,6 +66,20 @@ bare_ipc_close(bare_ipc_t *ipc) { uv_mutex_unlock(&ipc->lock); } +void +bare_ipc_end(bare_ipc_t *ipc) { + uv_mutex_lock(&ipc->lock); + + if (ipc->port != NULL) { + bare_queue_end(ipc->port); + + // Let a poll see that writes now fail. + bare_ipc__signal(ipc); + } + + uv_mutex_unlock(&ipc->lock); +} + void bare_ipc_destroy(bare_ipc_t *ipc) { bare_ipc_close(ipc); @@ -72,6 +87,8 @@ bare_ipc_destroy(bare_ipc_t *ipc) { bare_ipc__signal_destroy(ipc); uv_mutex_destroy(&ipc->lock); + + free(ipc); } void @@ -80,12 +97,12 @@ bare_ipc__dispatch(bare_ipc_t *ipc) { if (poll == NULL) return; - bare_ipc_poll_cb cb = poll->cb; + bare_ipc_poll_cb cb = atomic_load(&poll->cb); if (cb == NULL) return; // A closed ipc reads EOF and fails writes, so it is ready for both. - int ready = poll->events; + int ready = atomic_load(&poll->events); uv_mutex_lock(&ipc->lock); @@ -157,16 +174,33 @@ bare_ipc_write(bare_ipc_t *ipc, const void *data, size_t len) { } int -bare_ipc_poll_alloc(bare_ipc_poll_t **result) { +bare_ipc_poll_create(bare_ipc_t *ipc, bare_ipc_poll_t **result) { bare_ipc_poll_t *poll = malloc(sizeof(bare_ipc_poll_t)); if (poll == NULL) return -1; + poll->ipc = ipc; + poll->data = NULL; + + atomic_init(&poll->events, 0); + atomic_init(&poll->cb, NULL); + + bare_ipc__set_poll(ipc, poll); + *result = poll; return 0; } +void +bare_ipc_poll_destroy(bare_ipc_poll_t *poll) { + bare_ipc_poll_stop(poll); + + bare_ipc__set_poll(poll->ipc, NULL); + + free(poll); +} + void * bare_ipc_poll_get_data(bare_ipc_poll_t *poll) { return poll->data; @@ -181,3 +215,24 @@ bare_ipc_t * bare_ipc_poll_get_ipc(bare_ipc_poll_t *poll) { return poll->ipc; } + +int +bare_ipc_poll_start(bare_ipc_poll_t *poll, int events, bare_ipc_poll_cb cb) { + if (events == 0) return bare_ipc_poll_stop(poll); + + atomic_store(&poll->events, events); + atomic_store(&poll->cb, cb); + + // Level-triggered: signal once in case the events are already ready. + bare_ipc__signal(poll->ipc); + + return 0; +} + +int +bare_ipc_poll_stop(bare_ipc_poll_t *poll) { + atomic_store(&poll->events, 0); + atomic_store(&poll->cb, NULL); + + return 0; +} diff --git a/src/ipc.h b/src/ipc.h new file mode 100644 index 0000000..13b6666 --- /dev/null +++ b/src/ipc.h @@ -0,0 +1,65 @@ +#ifndef BARE_KIT_IPC_H +#define BARE_KIT_IPC_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +#include "queue.h" +#include "worklet.h" + +struct bare_ipc_s { + // NULL once closed, as closing gives up the ipc's share of the queue. + bare_queue_port_t *port; + uv_mutex_t lock; + + // The rest of a message too large for the last read. + bare_queue_message_t pending; + size_t offset; + + bare_ipc_poll_t *poll; + + // Owned by the ipc rather than the poll, as the worklet signals it for as long + // as the port is open. + void *signal; +}; + +struct bare_ipc_poll_s { + bare_ipc_t *ipc; + + _Atomic int events; + _Atomic bare_ipc_poll_cb cb; + + void *data; +}; + +// Implemented per platform. `bare_ipc__signal` may run on the worklet thread, so +// it may only touch state owned by the ipc. `bare_ipc__set_poll` waits for a +// running poll callback, unless called from it, so that a detached poll may be +// freed. +int +bare_ipc__signal_init(bare_ipc_t *ipc); + +void +bare_ipc__signal_destroy(bare_ipc_t *ipc); + +void +bare_ipc__signal(bare_ipc_t *ipc); + +void +bare_ipc__set_poll(bare_ipc_t *ipc, bare_ipc_poll_t *poll); + +// Calls the poll back with whichever of its events are ready, as a signal says +// that the queue changed but not how. Platforms call it on each wake. +void +bare_ipc__dispatch(bare_ipc_t *ipc); + +#ifdef __cplusplus +} +#endif + +#endif // BARE_KIT_IPC_H diff --git a/src/linux/symbols.c b/src/linux/symbols.c new file mode 100644 index 0000000..8dc902a --- /dev/null +++ b/src/linux/symbols.c @@ -0,0 +1,19 @@ +#define _GNU_SOURCE + +#include +#include + +#include "../symbols.h" + +void +bare_kit__expose_symbols(void) { + // As glibc ignores `-z global`, promote the library to the global scope in + // case it was loaded with `RTLD_LOCAL`. + Dl_info info; + + if (dladdr((void *) bare_kit__expose_symbols, &info) == 0 || info.dli_fname == NULL) return; + + void *library = dlopen(info.dli_fname, RTLD_LAZY | RTLD_NOLOAD | RTLD_GLOBAL); + + if (library) dlclose(library); +} diff --git a/src/platform.c b/src/platform.c new file mode 100644 index 0000000..38006e0 --- /dev/null +++ b/src/platform.c @@ -0,0 +1,16 @@ +#include "platform.h" + +void +bare_kit__on_thread_enter(void) {} + +void +bare_kit__on_thread_exit(void) {} + +void +bare_kit__retain_context(bare_worklet_options_t *result, const bare_worklet_options_t *options) {} + +void +bare_kit__release_context(const bare_worklet_options_t *options) {} + +void +bare_kit__publish_context(bare_t *bare, const bare_worklet_options_t *options) {} diff --git a/src/platform.h b/src/platform.h new file mode 100644 index 0000000..0144745 --- /dev/null +++ b/src/platform.h @@ -0,0 +1,40 @@ +#ifndef BARE_KIT_PLATFORM_H +#define BARE_KIT_PLATFORM_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void +bare_kit__on_thread_enter(void); + +void +bare_kit__on_thread_exit(void); + +/** + * Retain the handles of `options` that the worklet keeps for publishing into + * its own copy of the options, `result`. + */ +void +bare_kit__retain_context(bare_worklet_options_t *result, const bare_worklet_options_t *options); + +void +bare_kit__release_context(const bare_worklet_options_t *options); + +/** + * Publish the handles that only the embedder can produce for the addons of the + * process to retrieve with `bare_context_get()`. Must be called before the + * first `bare_load()`, as an addon only sees what was published before it was + * loaded. + */ +void +bare_kit__publish_context(bare_t *bare, const bare_worklet_options_t *options); + +#ifdef __cplusplus +} +#endif + +#endif // BARE_KIT_PLATFORM_H diff --git a/shared/queue.c b/src/queue.c similarity index 96% rename from shared/queue.c rename to src/queue.c index b66cb60..e44249c 100644 --- a/shared/queue.c +++ b/src/queue.c @@ -124,7 +124,7 @@ bare_queue_create(void) { } bare_queue_port_t * -bare_queue_open_uv(bare_queue_t *queue, uv_loop_t *loop, bare_queue_recv_cb on_recv, void *data) { +bare_queue_open_uv(bare_queue_t *queue, uv_loop_t *loop, bare_queue_cb on_recv, void *data) { int err; err = uv_async_init(loop, &queue->async, bare_queue__on_wakeup_uv); @@ -151,7 +151,7 @@ bare_queue_open_uv(bare_queue_t *queue, uv_loop_t *loop, bare_queue_recv_cb on_r } bare_queue_port_t * -bare_queue_open_thread(bare_queue_t *queue, bare_queue_signal_cb on_signal, void *data) { +bare_queue_open_thread(bare_queue_t *queue, bare_queue_cb on_signal, void *data) { uv_mutex_lock(&queue->lock); if (queue->thread_state != bare_queue_state_idle) { @@ -305,7 +305,7 @@ bare_queue_writable(bare_queue_port_t *port) { uv_mutex_lock(&queue->lock); - bool writable = !bare_queue__ring_full(bare_queue__outbox(port)) || bare_queue__peer_state(port) == bare_queue_state_closed; + bool writable = !bare_queue__ring_full(bare_queue__outbox(port)) || *bare_queue__state(port) >= bare_queue_state_ended || bare_queue__peer_state(port) == bare_queue_state_closed; uv_mutex_unlock(&queue->lock); @@ -327,5 +327,5 @@ bare_queue_destroy(bare_queue_t *queue) { void bare_queue_shutdown_uv(bare_queue_t *queue) { - if (queue->uv_state != bare_queue_state_idle) uv_close((uv_handle_t *) &queue->async, NULL); + uv_close((uv_handle_t *) &queue->async, NULL); } diff --git a/shared/queue.h b/src/queue.h similarity index 87% rename from shared/queue.h rename to src/queue.h index 6e0fe55..ac9a7ca 100644 --- a/shared/queue.h +++ b/src/queue.h @@ -12,16 +12,14 @@ extern "C" { // A bidirectional in-process message queue between the worklet, which runs on a // libuv loop, and the host, which is a plain native thread. Each direction is an // independent bounded ring of owned byte messages guarded by a single mutex. -// The worklet (uv) end is woken via a uv_async; the host end is woken via a -// caller-provided signal callback, which is the only platform-specific concern. +// The worklet (uv) end is woken via a uv_async and the host end via a callback. #define BARE_QUEUE_CAPACITY 1024 // Must be a power of two typedef struct bare_queue_s bare_queue_t; typedef struct bare_queue_port_s bare_queue_port_t; -typedef void (*bare_queue_signal_cb)(bare_queue_port_t *port); -typedef void (*bare_queue_recv_cb)(bare_queue_port_t *port); +typedef void (*bare_queue_cb)(bare_queue_port_t *port); enum { bare_queue_ok = 0, @@ -66,8 +64,8 @@ struct bare_queue_s { bool destroyed; - bare_queue_signal_cb on_signal_thread; - bare_queue_recv_cb on_recv_uv; + bare_queue_cb on_signal_thread; + bare_queue_cb on_recv_uv; bare_queue_port_t uv_port; bare_queue_port_t thread_port; @@ -89,7 +87,7 @@ bare_queue_destroy(bare_queue_t *queue); // on each one read until `bare_queue_would_block` and retry any blocked write. // It also fires once during this call if the host has already queued data. bare_queue_port_t * -bare_queue_open_uv(bare_queue_t *queue, uv_loop_t *loop, bare_queue_recv_cb on_recv, void *data); +bare_queue_open_uv(bare_queue_t *queue, uv_loop_t *loop, bare_queue_cb on_recv, void *data); // Opens the host (native thread) end. `on_signal` is called, possibly from the // worklet thread, under the same conditions as `on_recv` above, and the host @@ -98,7 +96,7 @@ bare_queue_open_uv(bare_queue_t *queue, uv_loop_t *loop, bare_queue_recv_cb on_r // open racing a worklet-thread signal can invoke it from two threads at once. // Returns NULL if the host end has already been opened. bare_queue_port_t * -bare_queue_open_thread(bare_queue_t *queue, bare_queue_signal_cb on_signal, void *data); +bare_queue_open_thread(bare_queue_t *queue, bare_queue_cb on_signal, void *data); // Copies `len` bytes to the peer. Returns `len`, `bare_queue_would_block` when // the ring is full, or `bare_queue_closed` once this end has ended or the peer @@ -126,14 +124,15 @@ bare_queue_close(bare_queue_port_t *port); // Non-consuming status for a poller. `readable` is true when a read would not // return `bare_queue_would_block` (data buffered, or EOF once the peer ended); -// `writable` is true when a write would not (space free, or the peer closed). +// `writable` is true when a write would not (space free, this end ended, or the +// peer closed). bool bare_queue_readable(bare_queue_port_t *port); bool bare_queue_writable(bare_queue_port_t *port); -// Retires the worklet (uv) end by closing its wakeup handle. Must be called on +// Retires the opened worklet (uv) end by closing its wakeup handle. Must be called on // the worklet thread, with the loop still to run so the close completes. void bare_queue_shutdown_uv(bare_queue_t *queue); diff --git a/src/resources.c b/src/resources.c new file mode 100644 index 0000000..07731b2 --- /dev/null +++ b/src/resources.c @@ -0,0 +1,15 @@ +#include +#include + +#include "resources.h" + +void +bare_kit__create_resources(js_env_t *env, const bare_worklet_options_t *options, js_value_t **directory, js_value_t **read) { + int err; + + err = js_get_null(env, directory); + assert(err == 0); + + err = js_get_null(env, read); + assert(err == 0); +} diff --git a/src/resources.h b/src/resources.h new file mode 100644 index 0000000..270c471 --- /dev/null +++ b/src/resources.h @@ -0,0 +1,23 @@ +#ifndef BARE_KIT_RESOURCES_H +#define BARE_KIT_RESOURCES_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Create the directory that relative filenames resolve against, and a function + * that reads a resource by its relative path where resources aren't files. + * Either is `null` if the platform has no such thing. + */ +void +bare_kit__create_resources(js_env_t *env, const bare_worklet_options_t *options, js_value_t **directory, js_value_t **read); + +#ifdef __cplusplus +} +#endif + +#endif // BARE_KIT_RESOURCES_H diff --git a/shared/uv/ipc.c b/src/standalone/ipc.c similarity index 68% rename from shared/uv/ipc.c rename to src/standalone/ipc.c index 47e1974..8ccc447 100644 --- a/shared/uv/ipc.c +++ b/src/standalone/ipc.c @@ -3,11 +3,13 @@ #include #include -#include "ipc.h" +#include "../ipc.h" +#include "../platform.h" -// Polls run on the signal thread. `running` is held across a callback so a poll -// cannot be torn down underneath it, and is recursive so the callback can stop -// or destroy its own poll, or its ipc. +// Polls run on a thread of their own rather than a host run loop, so that their +// callbacks are called the same way on every platform. `running` is held across +// a callback so a poll cannot be torn down underneath it, and is recursive so the +// callback can stop or destroy its own poll, or its ipc. typedef struct { uv_loop_t loop; @@ -48,6 +50,8 @@ static void bare_ipc__signal_thread(void *data) { bare_ipc_signal_t *signal = (bare_ipc_signal_t *) data; + bare_kit__on_thread_enter(); + int err; err = uv_run(&signal->loop, UV_RUN_DEFAULT); @@ -61,6 +65,8 @@ bare_ipc__signal_thread(void *data) { free(signal); } + + bare_kit__on_thread_exit(); } int @@ -141,73 +147,13 @@ bare_ipc__signal_destroy(bare_ipc_t *ipc) { ipc->signal = NULL; } -int -bare_ipc_poll_init(bare_ipc_poll_t *poll, bare_ipc_t *ipc) { - poll->ipc = ipc; - poll->events = 0; - poll->cb = NULL; - poll->data = NULL; - - bare_ipc_signal_t *signal = (bare_ipc_signal_t *) ipc->signal; - - uv_mutex_lock(&signal->running); - - ipc->poll = poll; - - uv_mutex_unlock(&signal->running); - - return 0; -} - void -bare_ipc_poll_destroy(bare_ipc_poll_t *poll) { - int err; - err = bare_ipc_poll_stop(poll); - assert(err == 0); - - bare_ipc_t *ipc = poll->ipc; - - bare_ipc_signal_t *signal = (bare_ipc_signal_t *) ipc->signal; - - // So the caller may free the poll once this returns. - uv_mutex_lock(&signal->running); - - ipc->poll = NULL; - - uv_mutex_unlock(&signal->running); -} - -int -bare_ipc_poll_start(bare_ipc_poll_t *poll, int events, bare_ipc_poll_cb cb) { - if (events == 0) return bare_ipc_poll_stop(poll); - - bare_ipc_t *ipc = poll->ipc; - +bare_ipc__set_poll(bare_ipc_t *ipc, bare_ipc_poll_t *poll) { bare_ipc_signal_t *signal = (bare_ipc_signal_t *) ipc->signal; uv_mutex_lock(&signal->running); - poll->events = events; - poll->cb = cb; - - uv_mutex_unlock(&signal->running); - - // Level-triggered: signal once in case the events are already ready. - bare_ipc__signal(ipc); - - return 0; -} - -int -bare_ipc_poll_stop(bare_ipc_poll_t *poll) { - bare_ipc_signal_t *signal = (bare_ipc_signal_t *) poll->ipc->signal; - - uv_mutex_lock(&signal->running); - - poll->events = 0; - poll->cb = NULL; + ipc->poll = poll; uv_mutex_unlock(&signal->running); - - return 0; } diff --git a/shared/android/suspension.c b/src/suspension.c similarity index 73% rename from shared/android/suspension.c rename to src/suspension.c index 4f6b6b8..952c4ce 100644 --- a/shared/android/suspension.c +++ b/src/suspension.c @@ -1,4 +1,4 @@ -#include "../suspension.h" +#include "suspension.h" int bare_suspension_init(bare_suspension_t *suspension) { @@ -6,7 +6,7 @@ bare_suspension_init(bare_suspension_t *suspension) { } int -bare_suspension_start(bare_suspension_t *result, int timeout) { +bare_suspension_start(bare_suspension_t *suspension, int timeout) { return timeout < 0 ? 30000 : timeout; } diff --git a/shared/suspension.h b/src/suspension.h similarity index 62% rename from shared/suspension.h rename to src/suspension.h index af9766a..e3b36d5 100644 --- a/shared/suspension.h +++ b/src/suspension.h @@ -7,21 +7,12 @@ extern "C" { typedef struct bare_suspension_s bare_suspension_t; -#if defined(BARE_KIT_DARWIN) || defined(BARE_KIT_IOS) -#include "apple/suspension.h" -#endif - -#if defined(BARE_KIT_ANDROID) -#include "android/suspension.h" -#endif - -#if defined(BARE_KIT_LINUX) -#include "linux/suspension.h" -#endif - -#if defined(BARE_KIT_WINDOWS) -#include "win32/suspension.h" +struct bare_suspension_s { +#if defined(BARE_KIT_IOS) + // Retained, as an expiration handler may outlive the suspension. + void *task; #endif +}; int bare_suspension_init(bare_suspension_t *suspension); diff --git a/src/symbols.c b/src/symbols.c new file mode 100644 index 0000000..15ca6a9 --- /dev/null +++ b/src/symbols.c @@ -0,0 +1,4 @@ +#include "symbols.h" + +void +bare_kit__expose_symbols(void) {} diff --git a/src/symbols.h b/src/symbols.h new file mode 100644 index 0000000..bf5b071 --- /dev/null +++ b/src/symbols.h @@ -0,0 +1,19 @@ +#ifndef BARE_KIT_SYMBOLS_H +#define BARE_KIT_SYMBOLS_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Make the symbols of Bare visible to the addons of the process, regardless of + * how the library was loaded. + */ +void +bare_kit__expose_symbols(void); + +#ifdef __cplusplus +} +#endif + +#endif // BARE_KIT_SYMBOLS_H diff --git a/src/win32/bare-kit.def b/src/win32/bare-kit.def new file mode 100644 index 0000000..0d6bf0e --- /dev/null +++ b/src/win32/bare-kit.def @@ -0,0 +1,30 @@ +EXPORTS + bare_worklet_optimize_for_memory + bare_worklet_teardown + bare_worklet_create + bare_worklet_destroy + bare_worklet_on_suspend + bare_worklet_on_wakeup + bare_worklet_on_idle + bare_worklet_on_resume + bare_worklet_on_exit + bare_worklet_get_data + bare_worklet_set_data + bare_worklet_start + bare_worklet_suspend + bare_worklet_resume + bare_worklet_wakeup + bare_worklet_terminate + bare_ipc_create + bare_ipc_close + bare_ipc_end + bare_ipc_destroy + bare_ipc_read + bare_ipc_write + bare_ipc_poll_create + bare_ipc_poll_destroy + bare_ipc_poll_get_data + bare_ipc_poll_set_data + bare_ipc_poll_get_ipc + bare_ipc_poll_start + bare_ipc_poll_stop diff --git a/shared/worklet.c b/src/worklet.c similarity index 62% rename from shared/worklet.c rename to src/worklet.c index 21705de..ffabc43 100644 --- a/shared/worklet.c +++ b/src/worklet.c @@ -9,20 +9,21 @@ #include #include -#include "context.h" -#include "events.h" +#include "platform.h" +#include "resources.h" #include "suspension.h" +#include "symbols.h" #include "worklet.bundle.h" #include "worklet.h" struct bare_worklet_state_s { bool finished; - // Guards the suspension state as well as the pushes. + // Guards the suspension state as well as `bare`, which is cleared before the + // worklet tears down. uv_mutex_t lock; - bool stopped; - bare_worklet_push_t *pushes; + bare_t *bare; bare_suspension_t suspension; @@ -30,31 +31,39 @@ struct bare_worklet_state_s { bool resuming; struct { - bare_suspend_cb suspend; + bare_worklet_suspend_cb suspend; void *suspend_data; - bare_wakeup_cb wakeup; + bare_worklet_wakeup_cb wakeup; void *wakeup_data; - bare_idle_cb idle; + bare_worklet_idle_cb idle; void *idle_data; - bare_resume_cb resume; + bare_worklet_resume_cb resume; void *resume_data; + + bare_worklet_exit_cb exit; + void *exit_data; } callbacks; }; static uv_once_t bare_worklet__init_guard = UV_ONCE_INIT; -// The state of the worklet whose thread this is, for replies, which carry only -// their push. -static uv_key_t bare_worklet__state; +// The worklets of the process that have started but not yet torn down. +static uv_mutex_t bare_worklet__running_lock; +static uv_cond_t bare_worklet__running_idle; +static int bare_worklet__running = 0; +static bool bare_worklet__torn_down = false; static void bare_worklet__on_init(void) { int err; - err = uv_key_create(&bare_worklet__state); + err = uv_mutex_init(&bare_worklet__running_lock); + assert(err == 0); + + err = uv_cond_init(&bare_worklet__running_idle); assert(err == 0); #ifdef SIGPIPE @@ -63,62 +72,43 @@ bare_worklet__on_init(void) { err = rlimit_set(rlimit_open_files, rlimit_infer); assert(err == 0); -} - -int -bare_worklet_alloc(bare_worklet_t **result) { - bare_worklet_t *worklet = malloc(sizeof(bare_worklet_t)); - - if (worklet == NULL) return -1; - - *result = worklet; - return 0; + bare_kit__expose_symbols(); } int -bare_worklet_init(bare_worklet_t *worklet, const bare_worklet_options_t *options) { +bare_worklet_create(const bare_worklet_options_t *options, bare_worklet_t **result) { uv_once(&bare_worklet__init_guard, bare_worklet__on_init); int err; - worklet->thread = 0; - - bare_worklet_state_t *state = malloc(sizeof(bare_worklet_state_t)); + bare_worklet_t *worklet = calloc(1, sizeof(bare_worklet_t)); + bare_worklet_state_t *state = calloc(1, sizeof(bare_worklet_state_t)); + bare_queue_t *queue = bare_queue_create(); - if (state == NULL) return -1; - - state->finished = false; - state->stopped = false; - state->pushes = NULL; - state->suspended = false; - state->resuming = false; - - err = uv_mutex_init(&state->lock); - assert(err == 0); - - memset(&state->callbacks, 0, sizeof(state->callbacks)); - - worklet->queue = bare_queue_create(); - - if (worklet->queue == NULL) { - uv_mutex_destroy(&state->lock); + if (worklet == NULL || state == NULL || queue == NULL) { + if (queue) bare_queue_destroy(queue); free(state); + free(worklet); return -1; } - worklet->state = state; - worklet->bare = NULL; + err = uv_mutex_init(&state->lock); + assert(err == 0); - memset(&worklet->options, 0, sizeof(worklet->options)); + worklet->state = state; + worklet->queue = queue; if (options) { worklet->options.memory_limit = options->memory_limit; - worklet->options.assets = options->assets == NULL ? NULL : strdup(options->assets); + + bare_kit__retain_context(&worklet->options, options); } + *result = worklet; + return 0; } @@ -127,7 +117,7 @@ bare_worklet_destroy(bare_worklet_t *worklet) { if (worklet->thread != 0) { // This must not block, as that causes an ANR on Android, so the detached // thread tears itself down. - bare_terminate(worklet->bare); + bare_worklet_terminate(worklet); uv_sem_post(worklet->finished); } else { // Never started, so the worklet's share of the queue is still ours. Closing @@ -140,11 +130,13 @@ bare_worklet_destroy(bare_worklet_t *worklet) { bare_queue_destroy(worklet->queue); } - free((char *) worklet->options.assets); + bare_kit__release_context(&worklet->options); + + free(worklet); } int -bare_worklet_on_suspend(bare_worklet_t *worklet, bare_suspend_cb cb, void *data) { +bare_worklet_on_suspend(bare_worklet_t *worklet, bare_worklet_suspend_cb cb, void *data) { worklet->state->callbacks.suspend = cb; worklet->state->callbacks.suspend_data = data; @@ -152,7 +144,7 @@ bare_worklet_on_suspend(bare_worklet_t *worklet, bare_suspend_cb cb, void *data) } int -bare_worklet_on_wakeup(bare_worklet_t *worklet, bare_wakeup_cb cb, void *data) { +bare_worklet_on_wakeup(bare_worklet_t *worklet, bare_worklet_wakeup_cb cb, void *data) { worklet->state->callbacks.wakeup = cb; worklet->state->callbacks.wakeup_data = data; @@ -160,7 +152,7 @@ bare_worklet_on_wakeup(bare_worklet_t *worklet, bare_wakeup_cb cb, void *data) { } int -bare_worklet_on_idle(bare_worklet_t *worklet, bare_idle_cb cb, void *data) { +bare_worklet_on_idle(bare_worklet_t *worklet, bare_worklet_idle_cb cb, void *data) { worklet->state->callbacks.idle = cb; worklet->state->callbacks.idle_data = data; @@ -168,13 +160,21 @@ bare_worklet_on_idle(bare_worklet_t *worklet, bare_idle_cb cb, void *data) { } int -bare_worklet_on_resume(bare_worklet_t *worklet, bare_resume_cb cb, void *data) { +bare_worklet_on_resume(bare_worklet_t *worklet, bare_worklet_resume_cb cb, void *data) { worklet->state->callbacks.resume = cb; worklet->state->callbacks.resume_data = data; return 0; } +int +bare_worklet_on_exit(bare_worklet_t *worklet, bare_worklet_exit_cb cb, void *data) { + worklet->state->callbacks.exit = cb; + worklet->state->callbacks.exit_data = data; + + return 0; +} + void * bare_worklet_get_data(bare_worklet_t *worklet) { return worklet->data; @@ -200,6 +200,8 @@ bare_worklet_optimize_for_memory(bool enabled) { return 0; } +// Shared by the worklets of the process. It can only be created once, so it lives +// until `bare_worklet_teardown()`, which waits for every running worklet first. static uv_once_t bare_worklet__platform_guard = UV_ONCE_INIT; static uv_thread_t bare_worklet__platform_thread; static uv_async_t bare_worklet__platform_shutdown; @@ -260,128 +262,39 @@ bare_worklet__on_platform_init(void) { uv_barrier_destroy(&bare_worklet__platform_ready); } -// Whether the push is still pending, which is compared by address alone, as the -// host may already have freed a push that has settled. Called with the lock held. -static bool -bare_worklet__push_pending(bare_worklet_state_t *state, bare_worklet_push_t *push) { - for (bare_worklet_push_t *next = state->pushes; next; next = next->next) { - if (next == push) return true; - } - - return false; -} - static void -bare_worklet__push_unlink(bare_worklet_state_t *state, bare_worklet_push_t *push) { - if (push->previous) push->previous->next = push->next; - else state->pushes = push->next; - - if (push->next) push->next->previous = push->previous; -} - -static js_value_t * -bare_worklet__on_push_reply(js_env_t *env, js_callback_info_t *info) { - int err; - - bare_worklet_push_t *push; - - size_t argc = 2; - js_value_t *argv[2]; - - err = js_get_callback_info(env, info, &argc, argv, NULL, (void **) &push); - assert(err == 0); - - bare_worklet_state_t *state = uv_key_get(&bare_worklet__state); - - uv_mutex_lock(&state->lock); - - bool pending = bare_worklet__push_pending(state, push); - - if (pending) bare_worklet__push_unlink(state, push); +bare_worklet__on_stopped(void) { + uv_mutex_lock(&bare_worklet__running_lock); - uv_mutex_unlock(&state->lock); - - if (!pending) return NULL; + if (--bare_worklet__running == 0) uv_cond_signal(&bare_worklet__running_idle); - assert(argc == 1 || argc == 2); + uv_mutex_unlock(&bare_worklet__running_lock); +} - if (argc == 1) { - err = js_get_null(env, &argv[1]); - assert(err == 0); - } +int +bare_worklet_teardown(void) { + uv_once(&bare_worklet__init_guard, bare_worklet__on_init); - char *error; + int err; - bool has_error; - err = js_is_string(env, argv[0], &has_error); - assert(err == 0); + uv_mutex_lock(&bare_worklet__running_lock); - if (has_error) { - size_t len; - err = js_get_value_string_utf8(env, argv[0], NULL, 0, &len); - assert(err == 0); + bare_worklet__torn_down = true; - len += 1 /* NULL */; + while (bare_worklet__running > 0) + uv_cond_wait(&bare_worklet__running_idle, &bare_worklet__running_lock); - error = malloc(len); + uv_mutex_unlock(&bare_worklet__running_lock); - err = js_get_value_string_utf8(env, argv[0], (utf8_t *) error, len, NULL); + if (bare_worklet__platform) { + err = uv_async_send(&bare_worklet__platform_shutdown); assert(err == 0); - } - - uv_buf_t reply; - bool has_reply; - err = js_is_typedarray(env, argv[1], &has_reply); - assert(err == 0); - - if (has_reply) { - err = js_get_typedarray_info(env, argv[1], NULL, (void **) &reply.base, (size_t *) &reply.len, NULL, NULL); + err = uv_thread_join(&bare_worklet__platform_thread); assert(err == 0); } - push->cb(push, has_error ? error : NULL, has_reply ? &reply : NULL); - - if (has_error) free(error); - - return NULL; -} - -static void -bare_worklet__on_push(js_env_t *env, js_value_t *onpush, void *context, void *data) { - int err; - - bare_worklet_state_t *state = (bare_worklet_state_t *) context; - - bare_worklet_push_t *push = (bare_worklet_push_t *) data; - - uv_mutex_lock(&state->lock); - - bool pending = bare_worklet__push_pending(state, push); - - uv_mutex_unlock(&state->lock); - - if (!pending) return; - - uv_buf_t payload = push->payload; - - js_value_t *args[2]; - - void *copy; - err = js_create_arraybuffer(env, payload.len, ©, &args[0]); - assert(err == 0); - - memcpy(copy, payload.base, payload.len); - - err = js_create_function(env, "reply", -1, bare_worklet__on_push_reply, data, &args[1]); - assert(err == 0); - - js_value_t *global; - err = js_get_global(env, &global); - assert(err == 0); - - err = js_call_function(env, global, onpush, 2, args, NULL); - assert(err == 0); + return 0; } static void @@ -390,7 +303,7 @@ bare_worklet__on_suspend(bare_t *bare, int linger, void *data) { if (state->finished) return; - if (state->callbacks.suspend) state->callbacks.suspend(bare, linger, state->callbacks.suspend_data); + if (state->callbacks.suspend) state->callbacks.suspend(linger, state->callbacks.suspend_data); } static void @@ -399,7 +312,7 @@ bare_worklet__on_wakeup(bare_t *bare, int deadline, void *data) { if (state->finished) return; - if (state->callbacks.wakeup) state->callbacks.wakeup(bare, deadline, state->callbacks.wakeup_data); + if (state->callbacks.wakeup) state->callbacks.wakeup(deadline, state->callbacks.wakeup_data); } static void @@ -421,7 +334,7 @@ bare_worklet__on_idle(bare_t *bare, void *data) { if (state->finished) return; - if (state->callbacks.idle) state->callbacks.idle(bare, state->callbacks.idle_data); + if (state->callbacks.idle) state->callbacks.idle(state->callbacks.idle_data); } static void @@ -436,7 +349,7 @@ bare_worklet__on_resume(bare_t *bare, void *data) { if (state->finished) return; - if (state->callbacks.resume) state->callbacks.resume(bare, state->callbacks.resume_data); + if (state->callbacks.resume) state->callbacks.resume(state->callbacks.resume_data); } static void @@ -587,9 +500,7 @@ bare_worklet__on_thread(void *opaque) { bare_worklet_state_t *state = worklet->state; - bare_kit__on_thread_enter(state); - - uv_key_set(&bare_worklet__state, state); + bare_kit__on_thread_enter(); uv_sem_t finished; err = uv_sem_init(&finished, 0); @@ -615,7 +526,7 @@ bare_worklet__on_thread(void *opaque) { err = bare_setup(&loop, bare_worklet__platform, &env, worklet->argc, worklet->argv, &options, &bare); assert(err == 0); - bare_kit__publish_context(bare); + bare_kit__publish_context(bare, &worklet->options); err = bare_on_suspend(bare, bare_worklet__on_suspend, state); assert(err == 0); @@ -629,7 +540,11 @@ bare_worklet__on_thread(void *opaque) { err = bare_on_resume(bare, bare_worklet__on_resume, state); assert(err == 0); - worklet->bare = bare; + uv_mutex_lock(&state->lock); + + state->bare = bare; + + uv_mutex_unlock(&state->lock); js_handle_scope_t *scope; err = js_open_handle_scope(env, &scope); @@ -685,52 +600,31 @@ bare_worklet__on_thread(void *opaque) { err = js_create_reference(env, on_signal, 1, &ipc.signal); assert(err == 0); - js_value_t *fn; - err = js_get_named_property(env, exports, "push", &fn); - assert(err == 0); - - js_threadsafe_function_t *push; - err = js_create_threadsafe_function(env, fn, 0, 1, NULL, NULL, (void *) state, bare_worklet__on_push, &push); - assert(err == 0); - - err = js_unref_threadsafe_function(env, push); - assert(err == 0); - - worklet->push = push; - js_value_t *start; err = js_get_named_property(env, exports, "start", &start); assert(err == 0); - js_value_t *args[3]; + js_value_t *args[4]; err = js_create_string_utf8(env, (const utf8_t *) worklet->filename, -1, &args[0]); assert(err == 0); - if (worklet->source.type == bare_worklet_source_buffer) { - const uv_buf_t source = worklet->source.buffer; - + if (worklet->source) { void *data; - err = js_create_arraybuffer(env, source.len, &data, &args[1]); + err = js_create_arraybuffer(env, worklet->len, &data, &args[1]); assert(err == 0); - memcpy(data, source.base, source.len); + memcpy(data, worklet->source, worklet->len); } else { err = js_get_null(env, &args[1]); assert(err == 0); } - if (worklet->options.assets) { - err = js_create_string_utf8(env, (const utf8_t *) worklet->options.assets, -1, &args[2]); - assert(err == 0); - } else { - err = js_get_null(env, &args[2]); - assert(err == 0); - } + bare_kit__create_resources(env, &worklet->options, &args[2], &args[3]); uv_barrier_wait(&worklet->ready); - js_call_function(env, module, start, 3, args, NULL); + js_call_function(env, module, start, 4, args, NULL); err = js_close_handle_scope(env, scope); assert(err == 0); @@ -740,34 +634,19 @@ bare_worklet__on_thread(void *opaque) { state->finished = true; - // Settled before parking, as the pushes belong to the host. - uv_mutex_lock(&state->lock); - - state->stopped = true; - - bare_worklet_push_t *pushes = state->pushes; + // Closed natively rather than from JS, so the host sees EOF on every exit path. + bare_queue_close(ipc_port); - state->pushes = NULL; + // From here the host no longer reaches the worklet, which can tear down + // without waiting to be destroyed. + uv_mutex_lock(&state->lock); - uv_mutex_unlock(&state->lock); + state->bare = NULL; - err = js_release_threadsafe_function(push, js_threadsafe_function_release); + err = bare_suspension_end(&state->suspension); assert(err == 0); - while (pushes) { - bare_worklet_push_t *next = pushes->next; - - pushes->cb(pushes, "Worklet terminated", NULL); - - pushes = next; - } - - // Closed natively rather than from JS, so the host sees EOF on every exit path. - bare_queue_close(ipc_port); - - uv_sem_wait(&finished); - - uv_sem_destroy(&finished); + uv_mutex_unlock(&state->lock); // Before deleting the reference, so no late signal reaches it. bare_queue_shutdown_uv(queue); @@ -782,18 +661,20 @@ bare_worklet__on_thread(void *opaque) { err = uv_loop_close(&loop); assert(err == 0); - bare_queue_destroy(queue); + bare_suspension_destroy(&state->suspension); - uv_mutex_lock(&state->lock); + if (state->callbacks.exit) state->callbacks.exit(exit_code, state->callbacks.exit_data); - err = bare_suspension_end(&state->suspension); - assert(err == 0); + bare_worklet__on_stopped(); - uv_mutex_unlock(&state->lock); + // The host may still open an ipc on the queue until it destroys the worklet. + uv_sem_wait(&finished); - bare_suspension_destroy(&state->suspension); + uv_sem_destroy(&finished); - bare_kit__on_thread_exit(state); + bare_queue_destroy(queue); + + bare_kit__on_thread_exit(); uv_mutex_destroy(&state->lock); @@ -801,19 +682,24 @@ bare_worklet__on_thread(void *opaque) { } int -bare_worklet_start(bare_worklet_t *worklet, const char *filename, const uv_buf_t *source, int argc, const char *argv[]) { +bare_worklet_start(bare_worklet_t *worklet, const char *filename, const void *source, size_t len, int argc, const char *argv[]) { int err; worklet->filename = filename; + worklet->source = source; + worklet->len = len; worklet->argc = argc; worklet->argv = argv; - if (source) { - worklet->source.type = bare_worklet_source_buffer; - worklet->source.buffer = *source; - } else { - worklet->source.type = bare_worklet_source_none; - } + uv_mutex_lock(&bare_worklet__running_lock); + + bool torn_down = bare_worklet__torn_down; + + if (!torn_down) bare_worklet__running++; + + uv_mutex_unlock(&bare_worklet__running_lock); + + if (torn_down) return -1; err = uv_barrier_init(&worklet->ready, 2); assert(err == 0); @@ -824,6 +710,8 @@ bare_worklet_start(bare_worklet_t *worklet, const char *filename, const uv_buf_t worklet->thread = 0; + bare_worklet__on_stopped(); + return err; } @@ -839,107 +727,84 @@ bare_worklet_start(bare_worklet_t *worklet, const char *filename, const uv_buf_t int bare_worklet_suspend(bare_worklet_t *worklet, int linger) { - if (worklet->thread == 0) return 0; + int err = 0; bare_worklet_state_t *state = worklet->state; uv_mutex_lock(&state->lock); - linger = bare_suspension_start(&state->suspension, linger); - assert(linger >= 0); + if (state->bare) { + linger = bare_suspension_start(&state->suspension, linger); + assert(linger >= 0); - state->suspended = true; + state->suspended = true; + + err = bare_suspend(state->bare, linger); + } uv_mutex_unlock(&state->lock); - return bare_suspend(worklet->bare, linger); + return err; } int bare_worklet_resume(bare_worklet_t *worklet) { - if (worklet->thread == 0) return 0; - - int err; + int err = 0; bare_worklet_state_t *state = worklet->state; uv_mutex_lock(&state->lock); - err = bare_suspension_end(&state->suspension); - assert(err == 0); + if (state->bare) { + err = bare_suspension_end(&state->suspension); + assert(err == 0); + + // Only a resume that follows a suspend is guaranteed to be observed by the + // worklet thread, as Bare ignores resuming a worklet that is already active. + if (state->suspended) { + state->suspended = false; + state->resuming = true; + } - // Only a resume that follows a suspend is guaranteed to be observed by the - // worklet thread, as Bare ignores resuming a worklet that is already active. - if (state->suspended) { - state->suspended = false; - state->resuming = true; + err = bare_resume(state->bare); } uv_mutex_unlock(&state->lock); - return bare_resume(worklet->bare); + return err; } int bare_worklet_wakeup(bare_worklet_t *worklet, int deadline) { - if (worklet->thread == 0) return 0; + int err = 0; bare_worklet_state_t *state = worklet->state; uv_mutex_lock(&state->lock); - deadline = bare_suspension_start(&state->suspension, deadline); - assert(deadline >= 0); + if (state->bare) { + deadline = bare_suspension_start(&state->suspension, deadline); + assert(deadline >= 0); + + err = bare_wakeup(state->bare, deadline); + } uv_mutex_unlock(&state->lock); - return bare_wakeup(worklet->bare, deadline); + return err; } int bare_worklet_terminate(bare_worklet_t *worklet) { - if (worklet->thread == 0) return 0; - - return bare_terminate(worklet->bare); -} - -int -bare_worklet_push(bare_worklet_t *worklet, bare_worklet_push_t *req, const uv_buf_t *payload, bare_worklet_push_cb cb) { - if (worklet->thread == 0) return -1; - - req->worklet = worklet; - req->payload = *payload; - req->cb = cb; - req->previous = NULL; + int err = 0; bare_worklet_state_t *state = worklet->state; uv_mutex_lock(&state->lock); - int err = -1; - - // The queue is unbounded, so this never blocks while holding the lock. - if (!state->stopped) err = js_call_threadsafe_function(worklet->push, (void *) req, js_threadsafe_function_nonblocking); - - if (err == 0) { - req->next = state->pushes; - - if (state->pushes) state->pushes->previous = req; - - state->pushes = req; - } + if (state->bare) err = bare_terminate(state->bare); uv_mutex_unlock(&state->lock); return err; } - -void * -bare_worklet_push_get_data(bare_worklet_push_t *req) { - return req->data; -} - -void -bare_worklet_push_set_data(bare_worklet_push_t *req, void *data) { - req->data = data; -} diff --git a/src/worklet.h b/src/worklet.h new file mode 100644 index 0000000..7411723 --- /dev/null +++ b/src/worklet.h @@ -0,0 +1,40 @@ +#ifndef BARE_KIT_WORKLET_H +#define BARE_KIT_WORKLET_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#include "queue.h" + +typedef struct bare_worklet_state_s bare_worklet_state_t; + +struct bare_worklet_s { + bare_worklet_options_t options; + + bare_worklet_state_t *state; + + const char *filename; + const void *source; + size_t len; + + int argc; + const char **argv; + + uv_thread_t thread; + uv_barrier_t ready; + uv_sem_t *finished; + + bare_queue_t *queue; + + void *data; +}; + +#ifdef __cplusplus +} +#endif + +#endif // BARE_KIT_WORKLET_H diff --git a/src/worklet.js b/src/worklet.js new file mode 100644 index 0000000..51465b9 --- /dev/null +++ b/src/worklet.js @@ -0,0 +1,181 @@ +const path = require('bare-path') +const fs = require('bare-fs') +const crypto = require('bare-crypto') +const { pathToFileURL } = require('bare-url') +const URL = require('bare-url') +const Module = require('bare-module') +const { startsWithWindowsDriveLetter } = require('bare-module-resolve') +const SystemLog = require('bare-system-logger') +const Console = require('bare-console') +const { Duplex } = require('bare-stream') + +const { protocol } = module + +global.console = new Console(new SystemLog()) + +// A signal from the queue means re-check both reads and a pending write. +class IPCStream extends Duplex { + constructor(native) { + super() + + this._native = native + this._reading = false + this._pendingWrite = null + } + + _read() { + this._reading = true + this._drain() + } + + _drain() { + if (!this._reading) return + + let chunk + while ((chunk = this._native.read()) !== undefined) { + if (chunk === null) { + this._reading = false + this.push(null) + return + } + + if (this.push(Buffer.from(chunk)) === false) { + this._reading = false + return + } + } + } + + _write(chunk, encoding, cb) { + this._send(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding), cb) + } + + _send(chunk, cb) { + const n = this._native.write(chunk) + + if (n === null) cb(IPC_CLOSED()) + else if (n < 0) this._pendingWrite = { chunk, cb } + else if (n < chunk.byteLength) this._pendingWrite = { chunk: chunk.subarray(n), cb } + else cb(null) + } + + _retry() { + if (this._pendingWrite === null) return + + const { chunk, cb } = this._pendingWrite + this._pendingWrite = null + + this._send(chunk, cb) + } + + // A half-close: the host reads EOF but may keep writing. streamx only calls + // _final once pending writes have drained. + _final(cb) { + this._native.end() + cb(null) + } + + // Lets the worklet exit once both ends are done, as the queue holds the loop + // open until then. + _destroy(err, cb) { + this._native.unref() + cb(null) + } + + _onsignal() { + this._retry() + this._drain() + } + + ref() { + if (!this.destroying) this._native.ref() + return this + } + + unref() { + this._native.unref() + return this + } +} + +// Returns the callback the worklet loop invokes when the queue signals. +exports.openIPC = function openIPC(native) { + const ipc = new IPCStream(native) + + Bare.IPC = ipc + + Bare.on('suspend', () => ipc.unref()).on('resume', () => ipc.ref()) + + return () => ipc._onsignal() +} + +exports.start = function start(filename, source, resources, readResource) { + if (resources !== null && isRelative(filename)) { + if (readResource !== null) { + extract(resources, filename, readResource) + + if (source === null) source = readResource(filename) + } + + filename = path.join(resources, filename) + } + + const url = toURL(filename) + + if (source === null) source = protocol.readSync(url) + else source = Buffer.from(source) + + return Module.loadSync(url, source, { protocol }) +} + +// The listing is extracted last, so that its presence means that every +// resource it lists has been. +function extract(resources, filename, readResource) { + const name = filename.slice(0, filename.length - path.extname(filename).length) + + const listing = path.join(resources, name + '.assets') + + if (fs.existsSync(listing)) return + + const keys = readResource(name + '.assets') + + if (keys === null) return + + for (const key of Buffer.from(keys).toString().split('\n')) { + if (key === '') continue + + const data = readResource(name + key) + + if (data === null) throw new Error(`Resource '${name + key}' is listed but missing`) + + write(path.join(resources, name + key), data) + } + + write(listing, keys) +} + +// Worklets may extract the same resources at once, so each file is moved into +// place whole. +function write(target, data) { + const tmp = target + '.' + crypto.randomBytes(8).toString('hex') + + fs.mkdirSync(path.dirname(target), { recursive: true }) + fs.writeFileSync(tmp, Buffer.from(data)) + fs.renameSync(tmp, target) +} + +function isRelative(filename) { + return !path.isAbsolute(filename) && URL.parse(filename) === null +} + +function toURL(pathOrURL) { + if (startsWithWindowsDriveLetter(pathOrURL)) return pathToFileURL(pathOrURL) + + return URL.parse(pathOrURL) || pathToFileURL(pathOrURL) +} + +function IPC_CLOSED() { + const err = new Error('IPC stream closed') + err.code = 'IPC_CLOSED' + return err +} diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 681a0a2..70f30e5 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -1,5 +1,151 @@ -add_subdirectory(shared) +list(APPEND tests + queue + queue-threads + queue-signal-lock + worklet-exit-code + worklet-ipc + worklet-ipc-after-destroy + worklet-ipc-destroy-in-callback + worklet-ipc-exit + worklet-ipc-half-close + worklet-ipc-host-end + worklet-ipc-short-read + worklet-ipc-single + worklet-ipc-write-after-close + worklet-suspend-resume + worklet-teardown + worklet-terminate-before-start +) -if(APPLE) - add_subdirectory(apple) +foreach(test IN LISTS tests) + add_executable(test_${test} ${test}.c) + + target_link_libraries( + test_${test} + PRIVATE + bare_kit + ) + + add_test( + NAME ${test} + COMMAND test_${test} + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} + ) + + set_tests_properties( + ${test} + PROPERTIES + TIMEOUT 120 + ) +endforeach() + +add_subdirectory(fixtures/addon) + +add_executable(test_worklet-addon-static worklet-addon.c) + +# Exported so that an addon resolves the symbols of Bare from the executable. +set_target_properties( + test_worklet-addon-static + PROPERTIES + ENABLE_EXPORTS ON + WINDOWS_EXPORT_ALL_SYMBOLS ON +) + +target_link_libraries( + test_worklet-addon-static + PRIVATE + bare_kit +) + +add_executable(test_worklet-addon-shared worklet-addon.c) + +target_link_libraries( + test_worklet-addon-shared + PRIVATE + bare_kit_shared +) + +# Links Bare Kit statically into a shared library of its own, like a language +# binding would. +add_library(test_embedder SHARED) + +if(WIN32) + target_sources( + test_embedder + PRIVATE + ../src/win32/bare-kit.def + ) +endif() + +target_link_libraries( + test_embedder + PRIVATE + bare_kit +) + +if(ANDROID) + target_link_options( + test_embedder + PRIVATE + "-Wl,-z,global" + ) endif() + +add_executable(test_worklet-addon-dynamic worklet-addon-dynamic.c) + +target_compile_definitions( + test_worklet-addon-dynamic + PRIVATE + BARE_KIT="$" +) + +add_dependencies(test_worklet-addon-dynamic bare_kit_shared) + +add_executable(test_worklet-addon-embedded worklet-addon-dynamic.c) + +target_compile_definitions( + test_worklet-addon-embedded + PRIVATE + BARE_KIT="$" +) + +add_dependencies(test_worklet-addon-embedded test_embedder) + +foreach(test IN ITEMS worklet-addon-dynamic worklet-addon-embedded) + target_include_directories( + test_${test} + PRIVATE + ../include + ) + + if(NOT WIN32) + target_link_libraries( + test_${test} + PRIVATE + ${CMAKE_DL_LIBS} + ) + endif() +endforeach() + +foreach(test IN ITEMS worklet-addon-static worklet-addon-shared worklet-addon-dynamic worklet-addon-embedded) + target_compile_definitions( + test_${test} + PRIVATE + ADDON="$,file:///,file://>$" + ) + + add_dependencies(test_${test} ${addon}_module) + + add_test( + NAME ${test} + COMMAND test_${test} + WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} + ) + + set_tests_properties( + ${test} + PROPERTIES + TIMEOUT 120 + ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$" + ) +endforeach() diff --git a/test/apple/CMakeLists.txt b/test/apple/CMakeLists.txt deleted file mode 100644 index 9ce9a3e..0000000 --- a/test/apple/CMakeLists.txt +++ /dev/null @@ -1,36 +0,0 @@ -list(APPEND tests - ipc-close-releases - ipc-handler-clears-writable - ipc-release-during-handler - ipc-retains-worklet - worklet-ipc - worklet-ipc-eof - worklet-ipc-large-write - worklet-push - worklet-push-error - worklet-push-releases - worklet-terminated -) - -foreach(test IN LISTS tests) - add_executable(${test} ${test}.m) - - target_link_libraries( - ${test} - PRIVATE - bare_kit - ) - - add_test( - NAME ${test} - COMMAND ${test} - WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} - ) - - set_tests_properties( - ${test} - PROPERTIES - TIMEOUT 120 - ) -endforeach() - diff --git a/test/apple/ipc-close-releases.m b/test/apple/ipc-close-releases.m deleted file mode 100644 index 5369c0b..0000000 --- a/test/apple/ipc-close-releases.m +++ /dev/null @@ -1,56 +0,0 @@ -#import -#import -#import -#import - -// A read waiting on `readable` holds the ipc. Closing completes the read with -// end-of-stream, which lets go, so the ipc is deallocated once released. - -static int deallocs = 0; - -static void (*dealloc)(id, SEL); - -static void -on_dealloc(id self, SEL cmd) { - deallocs++; - - dealloc(self, cmd); -} - -int -main() { - Method method = class_getInstanceMethod([BareIPC class], @selector(dealloc)); - - dealloc = (void (*)(id, SEL)) method_setImplementation(method, (IMP) on_dealloc); - - BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:nil]; - - NSString *source = @"BareKit.IPC.on('data', () => {})"; - - [worklet start:@"/app.js" source:[source dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; - - BareIPC *ipc = [[BareIPC alloc] initWithWorklet:worklet]; - - __block bool completed = false; - - [ipc read:^(NSData *data, NSError *error) { - assert(data == nil && error == nil); - - completed = true; - }]; - - [ipc close]; - [ipc release]; - - [worklet terminate]; - [worklet release]; - - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ - assert(completed); - assert(deallocs == 1); - - exit(0); - }); - - [[NSRunLoop currentRunLoop] run]; -} diff --git a/test/apple/ipc-handler-clears-writable.m b/test/apple/ipc-handler-clears-writable.m deleted file mode 100644 index 98181d0..0000000 --- a/test/apple/ipc-handler-clears-writable.m +++ /dev/null @@ -1,31 +0,0 @@ -#import -#import -#import - -// A readable handler that clears the writable handler must not have the cleared -// handler called after it for the same wake. - -int -main() { - BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:nil]; - - NSString *source = @"BareKit.IPC.on('data', () => {}).write('Hello!')"; - - [worklet start:@"/app.js" source:[source dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; - - BareIPC *ipc = [[BareIPC alloc] initWithWorklet:worklet]; - - ipc.writable = ^(BareIPC *ipc) {}; - - ipc.readable = ^(BareIPC *ipc) { - while ([ipc read] != nil) {} - - ipc.writable = nil; - }; - - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ - exit(0); - }); - - [[NSRunLoop currentRunLoop] run]; -} diff --git a/test/apple/ipc-release-during-handler.m b/test/apple/ipc-release-during-handler.m deleted file mode 100644 index ba87101..0000000 --- a/test/apple/ipc-release-during-handler.m +++ /dev/null @@ -1,45 +0,0 @@ -#import -#import -#import - -// Releasing the last reference to an ipc on the main thread, while its handler -// waits on the main thread, must not deadlock. - -int -main() { - BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:nil]; - - NSString *source = @"BareKit.IPC.on('data', () => {}).write('Hello!')"; - - [worklet start:@"/app.js" source:[source dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; - - BareIPC *ipc = [[BareIPC alloc] initWithWorklet:worklet]; - - [worklet release]; - - dispatch_semaphore_t entered = dispatch_semaphore_create(0); - - __block bool synced = false; - - ipc.readable = ^(BareIPC *ipc) { - ipc.readable = nil; - - dispatch_semaphore_signal(entered); - - dispatch_sync(dispatch_get_main_queue(), ^{ - synced = true; - }); - }; - - dispatch_semaphore_wait(entered, DISPATCH_TIME_FOREVER); - - [ipc release]; - - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ - assert(synced); - - exit(0); - }); - - [[NSRunLoop currentRunLoop] run]; -} diff --git a/test/apple/ipc-retains-worklet.m b/test/apple/ipc-retains-worklet.m deleted file mode 100644 index ba390eb..0000000 --- a/test/apple/ipc-retains-worklet.m +++ /dev/null @@ -1,33 +0,0 @@ -#import -#import -#import - -// An IPC is opened on a worklet and is meaningless without it, so it must hold -// it: after the caller releases its own reference the worklet has to still be -// there for the IPC to tear down against. -// -// This file is manual reference counting, so the retain the IPC takes is -// observable directly. - -int -main() { - BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:nil]; - - NSString *source = @"BareKit.IPC.write('Hello!')"; - - [worklet start:@"/app.js" source:[source dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; - - NSUInteger before = [worklet retainCount]; - - BareIPC *ipc = [[BareIPC alloc] initWithWorklet:worklet]; - - assert([worklet retainCount] == before + 1); - - // The caller is done with it; the IPC's reference is what keeps it alive. - [worklet release]; - - [ipc close]; - [ipc release]; - - return 0; -} diff --git a/test/apple/worklet-ipc-eof.m b/test/apple/worklet-ipc-eof.m deleted file mode 100644 index a8782b7..0000000 --- a/test/apple/worklet-ipc-eof.m +++ /dev/null @@ -1,25 +0,0 @@ -#import -#import - -int -main() { - BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:nil]; - - NSString *source = @"BareKit.IPC.write('bye'); BareKit.IPC.end()"; - - [worklet start:@"/app.js" source:[source dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; - - BareIPC *ipc = [[BareIPC alloc] initWithWorklet:worklet]; - - [ipc read:^(NSData *_Nullable data, NSError *_Nullable error) { - assert(data != nil); // The message arrives as its own read, before EOF - - [ipc read:^(NSData *_Nullable data, NSError *_Nullable error) { - assert(data == nil); // EOF must be signalled as nil, not an empty buffer - - exit(0); - }]; - }]; - - [[NSRunLoop currentRunLoop] run]; -} diff --git a/test/apple/worklet-ipc-large-write.m b/test/apple/worklet-ipc-large-write.m deleted file mode 100644 index 65b3f0e..0000000 --- a/test/apple/worklet-ipc-large-write.m +++ /dev/null @@ -1,34 +0,0 @@ -#import -#import - -static char buffer[4 * 1024 * 1024]; - -int -main() { - BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:nil]; - - NSString *source = @"BareKit.IPC.on('data', (data) => BareKit.IPC.write(data))"; - - [worklet start:@"/app.js" source:[source dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; - - BareIPC *ipc = [[BareIPC alloc] initWithWorklet:worklet]; - - [ipc write:[[NSData alloc] initWithBytesNoCopy:buffer length:sizeof(buffer)] - completion:^(NSError *_Nullable error) { - __block NSInteger received = 0; - - ipc.readable = ^(BareIPC *ipc) { - NSData *data = [ipc read]; - - assert(data != nil); - - received += data.length; - - if (received == sizeof(buffer)) { - exit(0); - } - }; - }]; - - [[NSRunLoop currentRunLoop] run]; -} diff --git a/test/apple/worklet-ipc.m b/test/apple/worklet-ipc.m deleted file mode 100644 index 4362723..0000000 --- a/test/apple/worklet-ipc.m +++ /dev/null @@ -1,28 +0,0 @@ -#import -#import - -int -main() { - BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:nil]; - - NSString *source = @"BareKit.IPC.on('data', (data) => BareKit.IPC.write(data)).write('Hello!')"; - - [worklet start:@"/app.js" source:[source dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; - - BareIPC *ipc = [[BareIPC alloc] initWithWorklet:worklet]; - - [ipc read:^(NSData *_Nullable data, NSError *_Nullable error) { - NSLog(@"%@", data); - - [ipc write:[@"Hello back!" dataUsingEncoding:NSUTF8StringEncoding] - completion:^(NSError *_Nullable error) { - [ipc read:^(NSData *_Nullable data, NSError *_Nullable error) { - NSLog(@"%@", data); - - exit(0); - }]; - }]; - }]; - - [[NSRunLoop currentRunLoop] run]; -} diff --git a/test/apple/worklet-push-error.m b/test/apple/worklet-push-error.m deleted file mode 100644 index d96547e..0000000 --- a/test/apple/worklet-push-error.m +++ /dev/null @@ -1,21 +0,0 @@ -#import -#import - -int -main() { - BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:nil]; - - NSString *source = @"BareKit.on('push', (data, reply) => reply(new Error('Abort!'), null))"; - - [worklet start:@"/app.js" source:[source dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; - - [worklet push:@"Push payload" - encoding:NSUTF8StringEncoding - completion:^(NSString *_Nullable reply, NSError *_Nullable error) { - NSLog(@"%@", error); - - exit(0); - }]; - - [[NSRunLoop currentRunLoop] run]; -} diff --git a/test/apple/worklet-push-releases.m b/test/apple/worklet-push-releases.m deleted file mode 100644 index 3ba48b3..0000000 --- a/test/apple/worklet-push-releases.m +++ /dev/null @@ -1,53 +0,0 @@ -#import -#import -#import -#import - -// A push releases its context once the reply has been delivered, both when the -// worklet replies and when the worklet is no longer running. - -static int deallocs = 0; - -static void (*dealloc)(id, SEL); - -static void -on_dealloc(id self, SEL cmd) { - deallocs++; - - dealloc(self, cmd); -} - -int -main() { - Method method = class_getInstanceMethod(NSClassFromString(@"BareWorkletPushContext"), @selector(dealloc)); - - dealloc = (void (*)(id, SEL)) method_setImplementation(method, (IMP) on_dealloc); - - BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:nil]; - - NSString *source = @"BareKit.on('push', (data, reply) => reply(null, 'Hello world!'))"; - - [worklet start:@"/app.js" source:[source dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; - - [worklet push:@"Push payload" - encoding:NSUTF8StringEncoding - completion:^(NSString *_Nullable reply, NSError *_Nullable error) { - assert(error == nil); - - [worklet terminate]; - - [worklet push:@"Push payload" - encoding:NSUTF8StringEncoding - completion:^(NSString *_Nullable reply, NSError *_Nullable error) { - assert(error != nil); - - dispatch_async(dispatch_get_main_queue(), ^{ - assert(deallocs == 2); - - exit(0); - }); - }]; - }]; - - [[NSRunLoop currentRunLoop] run]; -} diff --git a/test/apple/worklet-push.m b/test/apple/worklet-push.m deleted file mode 100644 index 956edd5..0000000 --- a/test/apple/worklet-push.m +++ /dev/null @@ -1,21 +0,0 @@ -#import -#import - -int -main() { - BareWorklet *worklet = [[BareWorklet alloc] initWithConfiguration:nil]; - - NSString *source = @"BareKit.on('push', (data, reply) => reply(null, 'Hello world!'))"; - - [worklet start:@"/app.js" source:[source dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; - - [worklet push:@"Push payload" - encoding:NSUTF8StringEncoding - completion:^(NSString *_Nullable reply, NSError *_Nullable error) { - NSLog(@"%@", reply); - - exit(0); - }]; - - [[NSRunLoop currentRunLoop] run]; -} diff --git a/test/apple/worklet-terminated.m b/test/apple/worklet-terminated.m deleted file mode 100644 index 5c23c0b..0000000 --- a/test/apple/worklet-terminated.m +++ /dev/null @@ -1,39 +0,0 @@ -#import -#import -#import - -// A terminated worklet refuses to open an ipc or to start, whether or not it -// was started before. - -int -main() { - BareWorklet *unstarted = [[BareWorklet alloc] initWithConfiguration:nil]; - - [unstarted terminate]; - - assert([[BareIPC alloc] initWithWorklet:unstarted] == nil); - - bool raised = false; - - @try { - [unstarted start:@"/app.js" source:[@"" dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; - } @catch (NSException *exception) { - raised = true; - } - - assert(raised); - - [unstarted release]; - - BareWorklet *started = [[BareWorklet alloc] initWithConfiguration:nil]; - - [started start:@"/app.js" source:[@"" dataUsingEncoding:NSUTF8StringEncoding] arguments:@[]]; - - [started terminate]; - - assert([[BareIPC alloc] initWithWorklet:started] == nil); - - [started release]; - - return 0; -} diff --git a/test/fixtures/addon/CMakeLists.txt b/test/fixtures/addon/CMakeLists.txt new file mode 100644 index 0000000..44a0425 --- /dev/null +++ b/test/fixtures/addon/CMakeLists.txt @@ -0,0 +1,9 @@ +add_bare_module(addon INSTALL OFF) + +target_sources( + ${addon} + PRIVATE + binding.c +) + +set(addon ${addon} PARENT_SCOPE) diff --git a/test/fixtures/addon/binding.c b/test/fixtures/addon/binding.c new file mode 100644 index 0000000..2a0d082 --- /dev/null +++ b/test/fixtures/addon/binding.c @@ -0,0 +1,13 @@ +#include +#include +#include + +static js_value_t * +addon_exports(js_env_t *env, js_value_t *exports) { + int err = js_create_string_utf8(env, (const utf8_t *) "Hello from addon", -1, &exports); + assert(err == 0); + + return exports; +} + +BARE_MODULE(addon, addon_exports) diff --git a/test/fixtures/addon/package.json b/test/fixtures/addon/package.json new file mode 100644 index 0000000..04fca4a --- /dev/null +++ b/test/fixtures/addon/package.json @@ -0,0 +1,4 @@ +{ + "name": "addon", + "version": "1.0.0" +} diff --git a/test/leaks.txt b/test/leaks.txt new file mode 100644 index 0000000..d85efae --- /dev/null +++ b/test/leaks.txt @@ -0,0 +1,8 @@ +# https://clang.llvm.org/docs/LeakSanitizer.html#suppressions + +# The pages the Objective-C runtime keeps for the autorelease pools of a thread. +leak:objc_autoreleasePoolPush + +# The continuations libdispatch caches per thread once released. +leak:_dispatch_continuation_alloc_from_heap +leak:_dispatch_continuation_pop diff --git a/test/shared/queue-signal-lock.c b/test/queue-signal-lock.c similarity index 98% rename from test/shared/queue-signal-lock.c rename to test/queue-signal-lock.c index e06042c..c60210e 100644 --- a/test/shared/queue-signal-lock.c +++ b/test/queue-signal-lock.c @@ -2,7 +2,7 @@ #include #include -#include "../../shared/queue.h" +#include "../src/queue.h" // A signal callback must run with the queue's lock held. Without that the peer // can retire its end - and free whatever the callback touches - between the diff --git a/test/shared/queue-threads.c b/test/queue-threads.c similarity index 98% rename from test/shared/queue-threads.c rename to test/queue-threads.c index 94714c1..601d9ae 100644 --- a/test/shared/queue-threads.c +++ b/test/queue-threads.c @@ -4,7 +4,7 @@ #include #include -#include "../../shared/queue.h" +#include "../src/queue.h" // Exercises the queue across a real thread boundary: the main thread produces // on the thread port while a uv thread consumes on the uv port. Verifies every diff --git a/test/shared/queue.c b/test/queue.c similarity index 66% rename from test/shared/queue.c rename to test/queue.c index 631b6c5..3b17200 100644 --- a/test/shared/queue.c +++ b/test/queue.c @@ -3,7 +3,7 @@ #include #include -#include "../../shared/queue.h" +#include "../src/queue.h" static int signaled = 0; static int uv_received = 0; @@ -30,7 +30,8 @@ main() { // Host writes, then the worklet opens. bare_queue_port_t *producer = bare_queue_open_thread(q, on_signal, NULL); - assert(bare_queue_write(producer, "early", 5) == 5); + err = bare_queue_write(producer, "early", 5); + assert(err == 5); uv_received = 0; bare_queue_open_uv(q, loop, on_recv_uv, NULL); @@ -38,6 +39,8 @@ main() { assert(err >= 0); assert(uv_received == 1); + bare_queue_close(producer); + bare_queue_shutdown_uv(q); err = uv_run(loop, UV_RUN_DEFAULT); assert(err == 0); @@ -49,12 +52,15 @@ main() { // Worklet writes, then the host opens: it is signalled during open. bare_queue_port_t *producer = bare_queue_open_uv(q, loop, on_recv_uv, NULL); - assert(bare_queue_write(producer, "early", 5) == 5); + err = bare_queue_write(producer, "early", 5); + assert(err == 5); int before = signaled; - bare_queue_open_thread(q, on_signal, NULL); + bare_queue_port_t *consumer = bare_queue_open_thread(q, on_signal, NULL); assert(signaled == before + 1); + bare_queue_close(consumer); + bare_queue_shutdown_uv(q); err = uv_run(loop, UV_RUN_DEFAULT); assert(err == 0); @@ -70,12 +76,15 @@ main() { assert(!bare_queue_readable(u) && bare_queue_writable(u)); assert(!bare_queue_readable(t) && bare_queue_writable(t)); - assert(bare_queue_write(t, "x", 1) == 1); + err = bare_queue_write(t, "x", 1); + + assert(err == 1); assert(bare_queue_readable(u)); bare_queue_close(t); assert(bare_queue_writable(u)); // peer closed, so a write fails rather than blocks - assert(bare_queue_write(u, "y", 1) == bare_queue_closed); + err = bare_queue_write(u, "y", 1); + assert(err == bare_queue_closed); assert(bare_queue_readable(u)); // buffered data, then EOF bare_queue_shutdown_uv(q); @@ -98,15 +107,21 @@ main() { assert(signaled == before + 1); assert(bare_queue_readable(t)); - assert(bare_queue_read(t, &data, &len) == bare_queue_ok && len == 0); - assert(bare_queue_write(u, "more", 4) == bare_queue_closed); + err = bare_queue_read(t, &data, &len); + assert(err == bare_queue_ok && len == 0); + err = bare_queue_write(u, "more", 4); + assert(err == bare_queue_closed); assert(bare_queue_writable(t)); - assert(bare_queue_write(t, "late", 4) == 4); - assert(bare_queue_read(u, &data, &len) == bare_queue_ok); + err = bare_queue_write(t, "late", 4); + assert(err == 4); + err = bare_queue_read(u, &data, &len); + assert(err == bare_queue_ok); assert(len == 4 && memcmp(data, "late", 4) == 0); free(data); + bare_queue_close(t); + bare_queue_shutdown_uv(q); err = uv_run(loop, UV_RUN_DEFAULT); assert(err == 0); @@ -119,7 +134,8 @@ main() { bare_queue_port_t *t = bare_queue_open_thread(q, on_signal, NULL); assert(t != NULL); - assert(bare_queue_open_thread(q, on_signal, NULL) == NULL); + bare_queue_port_t *other = bare_queue_open_thread(q, on_signal, NULL); + assert(other == NULL); bare_queue_destroy(q); bare_queue_close(t); @@ -139,8 +155,10 @@ main() { void *data; size_t len; - assert(bare_queue_read(t, &data, &len) == bare_queue_ok && len == 0); - assert(bare_queue_write(t, "late", 4) == bare_queue_closed); + err = bare_queue_read(t, &data, &len); + assert(err == bare_queue_ok && len == 0); + err = bare_queue_write(t, "late", 4); + assert(err == bare_queue_closed); bare_queue_close(t); } @@ -154,41 +172,54 @@ main() { size_t len; // Empty reads block on both ends. - assert(bare_queue_read(uv, &data, &len) == bare_queue_would_block); - assert(bare_queue_read(thread, &data, &len) == bare_queue_would_block); + err = bare_queue_read(uv, &data, &len); + assert(err == bare_queue_would_block); + err = bare_queue_read(thread, &data, &len); + assert(err == bare_queue_would_block); // Host -> worklet. - assert(bare_queue_write(thread, "ping", 4) == 4); - assert(bare_queue_read(uv, &data, &len) == bare_queue_ok); + err = bare_queue_write(thread, "ping", 4); + assert(err == 4); + err = bare_queue_read(uv, &data, &len); + assert(err == bare_queue_ok); assert(len == 4 && memcmp(data, "ping", 4) == 0); free(data); - assert(bare_queue_read(uv, &data, &len) == bare_queue_would_block); + err = bare_queue_read(uv, &data, &len); + assert(err == bare_queue_would_block); // Worklet -> host, and the host is signalled. int before = signaled; - assert(bare_queue_write(uv, "pong", 4) == 4); + err = bare_queue_write(uv, "pong", 4); + assert(err == 4); assert(signaled == before + 1); - assert(bare_queue_read(thread, &data, &len) == bare_queue_ok); + err = bare_queue_read(thread, &data, &len); + assert(err == bare_queue_ok); assert(len == 4 && memcmp(data, "pong", 4) == 0); free(data); // Wakes are coalesced: only a write into an empty ring signals. before = signaled; - assert(bare_queue_write(uv, "a", 1) == 1); - assert(bare_queue_write(uv, "b", 1) == 1); + err = bare_queue_write(uv, "a", 1); + assert(err == 1); + err = bare_queue_write(uv, "b", 1); + assert(err == 1); assert(signaled == before + 1); - assert(bare_queue_read(thread, &data, &len) == bare_queue_ok && len == 1); + err = bare_queue_read(thread, &data, &len); + assert(err == bare_queue_ok && len == 1); free(data); - assert(bare_queue_read(thread, &data, &len) == bare_queue_ok && len == 1); + err = bare_queue_read(thread, &data, &len); + assert(err == bare_queue_ok && len == 1); free(data); // A host write wakes the worklet loop. uv_received = 0; - assert(bare_queue_write(thread, "z", 1) == 1); + err = bare_queue_write(thread, "z", 1); + assert(err == 1); err = uv_run(loop, UV_RUN_NOWAIT); assert(err >= 0); assert(uv_received == 1); - assert(bare_queue_read(uv, &data, &len) == bare_queue_ok && len == 1); + err = bare_queue_read(uv, &data, &len); + assert(err == bare_queue_ok && len == 1); free(data); // Backpressure: fill the ring, then the next write blocks. @@ -196,11 +227,13 @@ main() { while (bare_queue_write(uv, "x", 1) == 1) n++; assert(n == BARE_QUEUE_CAPACITY - 1); - assert(bare_queue_write(uv, "x", 1) == bare_queue_would_block); + err = bare_queue_write(uv, "x", 1); + assert(err == bare_queue_would_block); // Draining the full ring wakes the worklet so it can retry the blocked write. uv_received = 0; - assert(bare_queue_read(thread, &data, &len) == bare_queue_ok && len == 1); + err = bare_queue_read(thread, &data, &len); + assert(err == bare_queue_ok && len == 1); free(data); n--; err = uv_run(loop, UV_RUN_NOWAIT); @@ -214,16 +247,21 @@ main() { assert(n == 0); // Zero-length writes never enqueue, so they cannot be read as EOF. - assert(bare_queue_write(uv, "", 0) == 0); - assert(bare_queue_read(thread, &data, &len) == bare_queue_would_block); + err = bare_queue_write(uv, "", 0); + assert(err == 0); + err = bare_queue_read(thread, &data, &len); + assert(err == bare_queue_would_block); // Closing one end surfaces EOF on the other, and further writes are rejected. bare_queue_close(uv); - assert(bare_queue_read(thread, &data, &len) == bare_queue_ok && len == 0); - assert(bare_queue_write(thread, "late", 4) == bare_queue_closed); + err = bare_queue_read(thread, &data, &len); + assert(err == bare_queue_ok && len == 0); + err = bare_queue_write(thread, "late", 4); + assert(err == bare_queue_closed); bare_queue_close(thread); - assert(bare_queue_read(uv, &data, &len) == bare_queue_ok && len == 0); + err = bare_queue_read(uv, &data, &len); + assert(err == bare_queue_ok && len == 0); bare_queue_shutdown_uv(queue); diff --git a/test/shared/CMakeLists.txt b/test/shared/CMakeLists.txt deleted file mode 100644 index 2018697..0000000 --- a/test/shared/CMakeLists.txt +++ /dev/null @@ -1,50 +0,0 @@ -list(APPEND tests - queue - queue-threads - queue-signal-lock - worklet-assets - worklet-destroy-before-start - worklet-exit-eof - worklet-ipc - worklet-ipc-after-destroy - worklet-ipc-destroy-in-callback - worklet-ipc-half-close - worklet-ipc-large-write - worklet-ipc-short-read - worklet-ipc-single - worklet-ipc-write-after-close - worklet-jsend-eof - worklet-push-after-exit - worklet-push-terminate - worklet-suspend-resume - worklet-suspend-resume-suspend - worklet-terminate-after-suspend - worklet-terminate-before-start -) - -execute_process( - COMMAND node fixtures/generate.js - WORKING_DIRECTORY ${CMAKE_CURRENT_LIST_DIR} -) - -foreach(test IN LISTS tests) - add_executable(shared_${test} ${test}.c) - - target_link_libraries( - shared_${test} - PRIVATE - bare_worklet - ) - - add_test( - NAME ${test} - COMMAND shared_${test} - WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} - ) - - set_tests_properties( - ${test} - PROPERTIES - TIMEOUT 120 - ) -endforeach() diff --git a/test/shared/assets/.gitignore b/test/shared/assets/.gitignore deleted file mode 100644 index d6b7ef3..0000000 --- a/test/shared/assets/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore diff --git a/test/shared/fixtures/.gitignore b/test/shared/fixtures/.gitignore deleted file mode 100644 index afb9b75..0000000 --- a/test/shared/fixtures/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -* -!.gitignore -!generate.js diff --git a/test/shared/fixtures/generate.js b/test/shared/fixtures/generate.js deleted file mode 100644 index f536e1d..0000000 --- a/test/shared/fixtures/generate.js +++ /dev/null @@ -1,18 +0,0 @@ -const fs = require('fs') -const path = require('path') -const Bundle = require('bare-bundle') - -const bundle = new Bundle() - .write('/foo.js', "console.log(require.asset('./bar.txt'), require.asset('./dir/baz.txt'))\n", { - main: true, - imports: { - './bar.txt': '/bar.txt', - './dir/baz.txt': '/dir/baz.txt' - } - }) - .write('/bar.txt', 'hello world\n', { asset: true }) - .write('/dir/baz.txt', 'hello world\n', { asset: true }) - -bundle.id = 'bundle-id' - -fs.writeFileSync(path.join(__dirname, 'assets.bundle'), bundle.toBuffer()) diff --git a/test/shared/worklet-assets.c b/test/shared/worklet-assets.c deleted file mode 100644 index 619e3ab..0000000 --- a/test/shared/worklet-assets.c +++ /dev/null @@ -1,23 +0,0 @@ -#include "../../shared/worklet.h" - -int -main() { - int e; - - bare_worklet_options_t options = { - .memory_limit = 0, - .assets = "test/shared/assets/assets.bundle", - }; - - bare_worklet_t worklet; - e = bare_worklet_init(&worklet, &options); - assert(e == 0); - - e = bare_worklet_start(&worklet, "test/shared/fixtures/assets.bundle", NULL, 0, NULL); - assert(e == 0); - - e = bare_worklet_terminate(&worklet); - assert(e == 0); - - bare_worklet_destroy(&worklet); -} diff --git a/test/shared/worklet-destroy-before-start.c b/test/shared/worklet-destroy-before-start.c deleted file mode 100644 index bf25fd3..0000000 --- a/test/shared/worklet-destroy-before-start.c +++ /dev/null @@ -1,12 +0,0 @@ -#include "../../shared/worklet.h" - -int -main() { - int e; - - bare_worklet_t worklet; - e = bare_worklet_init(&worklet, NULL); - assert(e == 0); - - bare_worklet_destroy(&worklet); -} diff --git a/test/shared/worklet-exit-eof.c b/test/shared/worklet-exit-eof.c deleted file mode 100644 index 917129e..0000000 --- a/test/shared/worklet-exit-eof.c +++ /dev/null @@ -1,47 +0,0 @@ -#include - -#include "../../shared/ipc.h" -#include "../../shared/worklet.h" - -// When the worklet exits on its own, the host reads EOF without having to -// terminate or destroy it first. - -int -main() { - int e; - - bare_worklet_t worklet; - e = bare_worklet_init(&worklet, NULL); - assert(e == 0); - - char *code = "setTimeout(() => Bare.exit(0), 50)"; - - uv_buf_t source = uv_buf_init(code, strlen(code)); - - e = bare_worklet_start(&worklet, "app.js", &source, 0, NULL); - assert(e == 0); - - bare_ipc_t ipc; - e = bare_ipc_init(&ipc, &worklet); - assert(e == 0); - - char data[BARE_IPC_READ_BUFFER_SIZE]; - int len; - - bool eof = false; - for (int i = 0; i < 200; i++) { - len = bare_ipc_read(&ipc, data, sizeof(data)); - assert(len >= 0 || len == bare_ipc_would_block); - if (len == 0) { - eof = true; - break; - } - uv_sleep(10); - } - - assert(eof); // The self-exit closed Bare.IPC and the host saw EOF - - bare_ipc_destroy(&ipc); - - bare_worklet_destroy(&worklet); -} diff --git a/test/shared/worklet-ipc-after-destroy.c b/test/shared/worklet-ipc-after-destroy.c deleted file mode 100644 index 28ce2f1..0000000 --- a/test/shared/worklet-ipc-after-destroy.c +++ /dev/null @@ -1,52 +0,0 @@ -#include -#include -#include -#include - -#include "../../shared/ipc.h" -#include "../../shared/worklet.h" - -// An ipc outlives its worklet: once the worklet is destroyed, it reads EOF and -// fails writes without touching the worklet again. - -int -main() { - int e; - - bare_worklet_t worklet; - e = bare_worklet_init(&worklet, NULL); - assert(e == 0); - - char *code = "Bare.IPC.on('data', () => {})"; - - uv_buf_t source = uv_buf_init(code, strlen(code)); - - e = bare_worklet_start(&worklet, "app.js", &source, 0, NULL); - assert(e == 0); - - bare_ipc_t ipc; - e = bare_ipc_init(&ipc, &worklet); - assert(e == 0); - - bare_worklet_destroy(&worklet); - - memset(&worklet, 0, sizeof(worklet)); - - char data[BARE_IPC_READ_BUFFER_SIZE]; - int len; - - bool eof = false; - for (int i = 0; i < 200 && !eof; i++) { - len = bare_ipc_read(&ipc, data, sizeof(data)); - assert(len >= 0 || len == bare_ipc_would_block); - if (len == 0) eof = true; - else uv_sleep(10); - } - - assert(eof); - - e = bare_ipc_write(&ipc, "late", 4); - assert(e == bare_ipc_error); - - bare_ipc_destroy(&ipc); -} diff --git a/test/shared/worklet-ipc-half-close.c b/test/shared/worklet-ipc-half-close.c deleted file mode 100644 index c24cec8..0000000 --- a/test/shared/worklet-ipc-half-close.c +++ /dev/null @@ -1,81 +0,0 @@ -#include -#include -#include -#include - -#include "../../shared/ipc.h" -#include "../../shared/worklet.h" - -// Ending Bare.IPC from the worklet is a half-close: the host reads EOF but may -// keep writing. - -static bool replied = false; -static char reply_buf[64]; - -static void -on_push(bare_worklet_push_t *req, const char *error, const uv_buf_t *reply) { - assert(error == NULL); - - memcpy(reply_buf, reply->base, reply->len); - reply_buf[reply->len] = '\0'; - - replied = true; -} - -int -main() { - int e; - - bare_worklet_t worklet; - e = bare_worklet_init(&worklet, NULL); - assert(e == 0); - - char *code = - "let received = ''\n" - "Bare.IPC.on('data', (data) => { received += data })\n" - "Bare.IPC.end()\n" - "BareKit.on('push', (data, reply) => reply(null, received))\n"; - - uv_buf_t source = uv_buf_init(code, strlen(code)); - - e = bare_worklet_start(&worklet, "app.js", &source, 0, NULL); - assert(e == 0); - - bare_ipc_t ipc; - e = bare_ipc_init(&ipc, &worklet); - assert(e == 0); - - char data[BARE_IPC_READ_BUFFER_SIZE]; - int len; - - bool eof = false; - for (int i = 0; i < 200 && !eof; i++) { - len = bare_ipc_read(&ipc, data, sizeof(data)); - assert(len >= 0 || len == bare_ipc_would_block); - if (len == 0) eof = true; - else uv_sleep(10); - } - - assert(eof); - - e = bare_ipc_write(&ipc, "hello", 5); - assert(e == 5); - - uv_sleep(100); - - uv_buf_t payload = uv_buf_init("status", 6); - - bare_worklet_push_t req; - e = bare_worklet_push(&worklet, &req, &payload, on_push); - assert(e == 0); - - for (int i = 0; i < 200 && !replied; i++) - uv_sleep(10); - - assert(replied); - assert(strcmp(reply_buf, "hello") == 0); - - bare_ipc_destroy(&ipc); - - bare_worklet_destroy(&worklet); -} diff --git a/test/shared/worklet-ipc-large-write.c b/test/shared/worklet-ipc-large-write.c deleted file mode 100644 index a12a6e9..0000000 --- a/test/shared/worklet-ipc-large-write.c +++ /dev/null @@ -1,119 +0,0 @@ -#include - -#include "../../shared/ipc.h" -#include "../../shared/worklet.h" - -#define BARE_IPC_LARGE_BUF_LEN 4 * 1024 * 1024 - -void -read_continuosly(bare_ipc_poll_t *poll); -void -write_continuosly(bare_ipc_poll_t *poll); - -const char BARE_IPC_LARGE_BUF[BARE_IPC_LARGE_BUF_LEN]; -uv_async_t finished; -size_t received = 0; -size_t written = 0; - -void -on_poll(bare_ipc_poll_t *poll, int events) { - int err = bare_ipc_poll_stop(poll); - assert(err == 0); - - if ((events & bare_ipc_readable) != 0) read_continuosly(poll); - if ((events & bare_ipc_writable) != 0) write_continuosly(poll); -} - -void -read_continuosly(bare_ipc_poll_t *poll) { - int err; - char data[BARE_IPC_READ_BUFFER_SIZE]; - int len; - - while (received != BARE_IPC_LARGE_BUF_LEN) { - len = bare_ipc_read(poll->ipc, data, sizeof(data)); - assert(len >= 0 || len == bare_ipc_would_block); - - if (len != bare_ipc_would_block) { - received += len; - } else { - err = bare_ipc_poll_start(poll, bare_ipc_readable, on_poll); - assert(err == 0); - - return; - } - } - - uv_async_send(&finished); -} - -void -write_continuosly(bare_ipc_poll_t *poll) { - int err; - - while (written != BARE_IPC_LARGE_BUF_LEN) { - err = bare_ipc_write(poll->ipc, &BARE_IPC_LARGE_BUF[written], BARE_IPC_LARGE_BUF_LEN - written); - assert(err >= 0 || err == bare_ipc_would_block); - - if (err != bare_ipc_would_block) { - written += err; - } else { - err = bare_ipc_poll_start(poll, bare_ipc_writable, on_poll); - assert(err == 0); - - return; - } - } - - read_continuosly(poll); -} - -void -on_finish(uv_async_t *handle) { - uv_close((uv_handle_t *) handle, NULL); -} - -int -main() { - int err; - - uv_loop_t *loop = uv_default_loop(); - err = uv_async_init(loop, &finished, on_finish); - assert(err == 0); - - bare_worklet_t worklet; - err = bare_worklet_init(&worklet, NULL); - assert(err == 0); - - char *code = "BareKit.IPC.on('data', (data) => BareKit.IPC.write(data))"; - uv_buf_t source = uv_buf_init(code, strlen(code)); - err = bare_worklet_start(&worklet, "app.js", &source, 0, NULL); - assert(err == 0); - - bare_ipc_t ipc; - err = bare_ipc_init(&ipc, &worklet); - assert(err == 0); - - bare_ipc_poll_t poll; - err = bare_ipc_poll_init(&poll, &ipc); - assert(err == 0); - - write_continuosly(&poll); - - err = uv_run(loop, UV_RUN_DEFAULT); - assert(err == 0); - - // Before the loop closes: the worklet's exit makes this end readable, and the - // poll's callback posts to this loop. - bare_ipc_poll_destroy(&poll); - - err = uv_loop_close(loop); - assert(err == 0); - - err = bare_worklet_terminate(&worklet); - assert(err == 0); - - bare_ipc_destroy(&ipc); - - bare_worklet_destroy(&worklet); -} diff --git a/test/shared/worklet-ipc-short-read.c b/test/shared/worklet-ipc-short-read.c deleted file mode 100644 index 470fee2..0000000 --- a/test/shared/worklet-ipc-short-read.c +++ /dev/null @@ -1,54 +0,0 @@ -#include -#include -#include -#include - -#include "../../shared/ipc.h" -#include "../../shared/worklet.h" - -// A message larger than the read buffer arrives over several reads. - -int -main() { - int e; - - bare_worklet_t worklet; - e = bare_worklet_init(&worklet, NULL); - assert(e == 0); - - char *code = "Bare.IPC.write('Hello world!')"; - - uv_buf_t source = uv_buf_init(code, strlen(code)); - - e = bare_worklet_start(&worklet, "app.js", &source, 0, NULL); - assert(e == 0); - - bare_ipc_t ipc; - e = bare_ipc_init(&ipc, &worklet); - assert(e == 0); - - char message[64]; - size_t received = 0; - - for (int i = 0; i < 200 && received < 12; i++) { - char data[5]; - int len = bare_ipc_read(&ipc, data, sizeof(data)); - assert(len > 0 || len == bare_ipc_would_block); - - if (len == bare_ipc_would_block) { - uv_sleep(10); - } else { - assert(len <= 5); - - memcpy(message + received, data, len); - received += len; - } - } - - assert(received == 12); - assert(memcmp(message, "Hello world!", 12) == 0); - - bare_ipc_destroy(&ipc); - - bare_worklet_destroy(&worklet); -} diff --git a/test/shared/worklet-ipc-single.c b/test/shared/worklet-ipc-single.c deleted file mode 100644 index eff9e17..0000000 --- a/test/shared/worklet-ipc-single.c +++ /dev/null @@ -1,36 +0,0 @@ -#include -#include -#include - -#include "../../shared/ipc.h" -#include "../../shared/worklet.h" - -// A second ipc on the same worklet is refused. - -int -main() { - int e; - - bare_worklet_t worklet; - e = bare_worklet_init(&worklet, NULL); - assert(e == 0); - - char *code = "Bare.IPC.on('data', () => {})"; - - uv_buf_t source = uv_buf_init(code, strlen(code)); - - e = bare_worklet_start(&worklet, "app.js", &source, 0, NULL); - assert(e == 0); - - bare_ipc_t ipc; - e = bare_ipc_init(&ipc, &worklet); - assert(e == 0); - - bare_ipc_t other; - e = bare_ipc_init(&other, &worklet); - assert(e < 0); - - bare_ipc_destroy(&ipc); - - bare_worklet_destroy(&worklet); -} diff --git a/test/shared/worklet-ipc-write-after-close.c b/test/shared/worklet-ipc-write-after-close.c deleted file mode 100644 index 9a97938..0000000 --- a/test/shared/worklet-ipc-write-after-close.c +++ /dev/null @@ -1,68 +0,0 @@ -#include -#include -#include -#include - -#include "../../shared/ipc.h" -#include "../../shared/worklet.h" - -// A pending worklet write must error, not hang, once the host closes its ipc. - -static bool replied = false; -static char reply_buf[64]; - -static void -on_push(bare_worklet_push_t *req, const char *error, const uv_buf_t *reply) { - assert(error == NULL); - - memcpy(reply_buf, reply->base, reply->len); - reply_buf[reply->len] = '\0'; - - replied = true; -} - -int -main() { - int e; - - bare_worklet_t worklet; - e = bare_worklet_init(&worklet, NULL); - assert(e == 0); - - char *code = - "let errored = false\n" - "Bare.IPC.on('error', () => { errored = true })\n" - "setInterval(() => Bare.IPC.write(Buffer.alloc(64)), 5)\n" - "BareKit.on('push', (data, reply) => reply(null, errored ? 'errored' : 'wedged'))\n"; - - uv_buf_t source = uv_buf_init(code, strlen(code)); - - e = bare_worklet_start(&worklet, "app.js", &source, 0, NULL); - assert(e == 0); - - bare_ipc_t ipc; - e = bare_ipc_init(&ipc, &worklet); - assert(e == 0); - - // Never read, so the queue fills and the worklet is left with a pending write. - uv_sleep(100); - - bare_ipc_destroy(&ipc); - - // Give the worklet time to retry that write against the closed peer. - uv_sleep(300); - - uv_buf_t payload = uv_buf_init("status", 6); - - bare_worklet_push_t req; - e = bare_worklet_push(&worklet, &req, &payload, on_push); - assert(e == 0); - - for (int i = 0; i < 200 && !replied; i++) - uv_sleep(10); - - assert(replied); - assert(strcmp(reply_buf, "errored") == 0); - - bare_worklet_destroy(&worklet); -} diff --git a/test/shared/worklet-ipc.c b/test/shared/worklet-ipc.c deleted file mode 100644 index 16e7c0c..0000000 --- a/test/shared/worklet-ipc.c +++ /dev/null @@ -1,154 +0,0 @@ -#include - -#include "../../shared/ipc.h" -#include "../../shared/worklet.h" - -const char *response = "Hello back!"; -uv_async_t finished; - -void -on_poll(bare_ipc_poll_t *poll, int events) { - int err; - char data[BARE_IPC_READ_BUFFER_SIZE]; - int len; - - err = bare_ipc_poll_stop(poll); - assert(err == 0); - - if ((events & bare_ipc_readable) != 0) { - len = bare_ipc_read(poll->ipc, data, sizeof(data)); - assert(len > 0); - - if (strncmp(data, response, len) == 0) { - printf("%.*s", (int) len, (char *) data); - uv_async_send(&finished); - return; - } else { - printf("%.*s\n", (int) len, (char *) data); - - err = bare_ipc_write(poll->ipc, response, strlen(response)); - assert(err >= 0 || err == bare_ipc_would_block); - - if (err != bare_ipc_would_block) { - len = bare_ipc_read(poll->ipc, data, sizeof(data)); - assert(len >= 0 || len == bare_ipc_would_block); - - if (len != bare_ipc_would_block) { - assert(strncmp(data, response, len) == 0); - printf("%.*s\n", (int) len, (char *) data); - uv_async_send(&finished); - return; - } else { - err = bare_ipc_poll_start(poll, bare_ipc_readable, on_poll); - assert(err == 0); - } - } else { - err = bare_ipc_poll_start(poll, bare_ipc_writable, on_poll); - assert(err == 0); - } - } - } - - if ((events & bare_ipc_writable) != 0) { - err = bare_ipc_write(poll->ipc, response, strlen(response)); - assert(err >= 0); - - len = bare_ipc_read(poll->ipc, data, sizeof(data)); - assert(len >= 0 || len == bare_ipc_would_block); - - if (len != bare_ipc_would_block) { - assert(strncmp(data, response, len) == 0); - printf("%.*s\n", (int) len, (char *) data); - uv_async_send(&finished); - return; - } else { - err = bare_ipc_poll_start(poll, bare_ipc_readable, on_poll); - assert(err == 0); - } - } -} - -void -on_finish(uv_async_t *handle) { - uv_close((uv_handle_t *) handle, NULL); -} - -int -main() { - int err; - - uv_loop_t *loop = uv_default_loop(); - err = uv_async_init(loop, &finished, on_finish); - assert(err == 0); - - bare_worklet_t worklet; - err = bare_worklet_init(&worklet, NULL); - assert(err == 0); - - char *code = "BareKit.IPC.on('data', (data) => BareKit.IPC.write(data)).write('Hello!')"; - uv_buf_t source = uv_buf_init(code, strlen(code)); - err = bare_worklet_start(&worklet, "app.js", &source, 0, NULL); - assert(err == 0); - - bare_ipc_t ipc; - err = bare_ipc_init(&ipc, &worklet); - assert(err == 0); - - bare_ipc_poll_t poll; - err = bare_ipc_poll_init(&poll, &ipc); - assert(err == 0); - - char data[BARE_IPC_READ_BUFFER_SIZE]; - int len; - len = bare_ipc_read(&ipc, data, sizeof(data)); - assert(len >= 0 || len == bare_ipc_would_block); - - if (len != bare_ipc_would_block) { - printf("%.*s\n", (int) len, (char *) data); - - err = bare_ipc_write(&ipc, response, strlen(response)); - assert(err >= 0 || err == bare_ipc_would_block); - - if (err != bare_ipc_would_block) { - len = bare_ipc_read(&ipc, data, sizeof(data)); - assert(len >= 0 || len == bare_ipc_would_block); - - if (len != bare_ipc_would_block) { - assert(strncmp(data, response, len) == 0); - printf("%.*s\n", (int) len, (char *) data); - } else { - err = bare_ipc_poll_start(&poll, bare_ipc_readable, on_poll); - assert(err == 0); - - err = uv_run(loop, UV_RUN_DEFAULT); - assert(err == 0); - } - } else { - err = bare_ipc_poll_start(&poll, bare_ipc_writable, on_poll); - assert(err == 0); - - err = uv_run(loop, UV_RUN_DEFAULT); - assert(err == 0); - } - } else { - err = bare_ipc_poll_start(&poll, bare_ipc_readable, on_poll); - assert(err == 0); - - err = uv_run(loop, UV_RUN_DEFAULT); - assert(err == 0); - } - - // Before the loop closes: the worklet's exit makes this end readable, and the - // poll's callback posts to this loop. - bare_ipc_poll_destroy(&poll); - - err = uv_loop_close(loop); - assert(err == 0); - - err = bare_worklet_terminate(&worklet); - assert(err == 0); - - bare_ipc_destroy(&ipc); - - bare_worklet_destroy(&worklet); -} diff --git a/test/shared/worklet-jsend-eof.c b/test/shared/worklet-jsend-eof.c deleted file mode 100644 index ebebbd4..0000000 --- a/test/shared/worklet-jsend-eof.c +++ /dev/null @@ -1,48 +0,0 @@ -#include - -#include "../../shared/ipc.h" -#include "../../shared/worklet.h" - -// Ending Bare.IPC from JS reaches the host as EOF, which the bindings turn into -// (nil, nil). - -int -main() { - int e; - - bare_worklet_t worklet; - e = bare_worklet_init(&worklet, NULL); - assert(e == 0); - - char *code = "setTimeout(() => Bare.IPC.end(), 50)"; - - uv_buf_t source = uv_buf_init(code, strlen(code)); - - e = bare_worklet_start(&worklet, "app.js", &source, 0, NULL); - assert(e == 0); - - bare_ipc_t ipc; - e = bare_ipc_init(&ipc, &worklet); - assert(e == 0); - - char data[BARE_IPC_READ_BUFFER_SIZE]; - int len; - - // Poll for up to ~2s for EOF. Expect read to return 0 once the worklet ends. - bool eof = false; - for (int i = 0; i < 200; i++) { - len = bare_ipc_read(&ipc, data, sizeof(data)); - assert(len >= 0 || len == bare_ipc_would_block); - if (len == 0) { - eof = true; - break; - } - uv_sleep(10); - } - - assert(eof); // The JS-side end reached the host as EOF - - bare_ipc_destroy(&ipc); - - bare_worklet_destroy(&worklet); -} diff --git a/test/shared/worklet-push-after-exit.c b/test/shared/worklet-push-after-exit.c deleted file mode 100644 index e84abaf..0000000 --- a/test/shared/worklet-push-after-exit.c +++ /dev/null @@ -1,39 +0,0 @@ -#include -#include -#include - -#include "../../shared/worklet.h" - -// Once the worklet's loop has stopped, a push fails rather than blocking or -// waiting for a reply that never comes. - -static void -on_push(bare_worklet_push_t *req, const char *error, const uv_buf_t *reply) { - assert(false); -} - -int -main() { - int e; - - bare_worklet_t worklet; - e = bare_worklet_init(&worklet, NULL); - assert(e == 0); - - char *code = "Bare.exit(0)"; - - uv_buf_t source = uv_buf_init(code, strlen(code)); - - e = bare_worklet_start(&worklet, "app.js", &source, 0, NULL); - assert(e == 0); - - uv_sleep(500); - - uv_buf_t payload = uv_buf_init("ping", 4); - - bare_worklet_push_t req; - e = bare_worklet_push(&worklet, &req, &payload, on_push); - assert(e < 0); - - bare_worklet_destroy(&worklet); -} diff --git a/test/shared/worklet-push-terminate.c b/test/shared/worklet-push-terminate.c deleted file mode 100644 index adcf254..0000000 --- a/test/shared/worklet-push-terminate.c +++ /dev/null @@ -1,52 +0,0 @@ -#include -#include -#include -#include - -#include "../../shared/worklet.h" - -// Pushes still pending when the worklet stops are each settled with an error, -// rather than lost. - -static atomic_int replies = 0; -static atomic_int errors = 0; - -static void -on_push(bare_worklet_push_t *req, const char *error, const uv_buf_t *reply) { - if (error) errors++; - else replies++; -} - -int -main() { - int e; - - bare_worklet_t worklet; - e = bare_worklet_init(&worklet, NULL); - assert(e == 0); - - char *code = "BareKit.on('push', (data, reply) => setTimeout(() => reply(null, 'late'), 500))"; - - uv_buf_t source = uv_buf_init(code, strlen(code)); - - e = bare_worklet_start(&worklet, "app.js", &source, 0, NULL); - assert(e == 0); - - uv_buf_t payload = uv_buf_init("ping", 4); - - bare_worklet_push_t reqs[10]; - - for (int i = 0; i < 10; i++) { - e = bare_worklet_push(&worklet, &reqs[i], &payload, on_push); - assert(e == 0); - } - - uv_sleep(30); - - bare_worklet_destroy(&worklet); - - for (int i = 0; i < 100 && errors < 10; i++) uv_sleep(10); - - assert(replies == 0); - assert(errors == 10); -} diff --git a/test/shared/worklet-suspend-resume-suspend.c b/test/shared/worklet-suspend-resume-suspend.c deleted file mode 100644 index fcad33b..0000000 --- a/test/shared/worklet-suspend-resume-suspend.c +++ /dev/null @@ -1,79 +0,0 @@ -#include - -#include "../../shared/worklet.h" - -static int suspend_calls = 0; -static int resume_calls = 0; -static int idle_calls = 0; - -static void -on_suspend(bare_t *bare, int linger, void *data) { - suspend_calls++; -} - -static void -on_idle(bare_t *bare, void *data) { - idle_calls++; -} - -static void -on_resume(bare_t *bare, void *data) { - resume_calls++; -} - -int -main() { - int e; - - bare_worklet_t worklet; - e = bare_worklet_init(&worklet, NULL); - assert(e == 0); - - e = bare_worklet_on_suspend(&worklet, on_suspend, NULL); - assert(e == 0); - - e = bare_worklet_on_idle(&worklet, on_idle, NULL); - assert(e == 0); - - e = bare_worklet_on_resume(&worklet, on_resume, NULL); - assert(e == 0); - - char *code = "console.log('Hello world')"; - - uv_buf_t source = uv_buf_init(code, strlen(code)); - - e = bare_worklet_start(&worklet, "app.js", &source, 0, NULL); - assert(e == 0); - - e = bare_worklet_suspend(&worklet, 10); - assert(e == 0); - - e = bare_worklet_resume(&worklet); - assert(e == 0); - - e = bare_worklet_suspend(&worklet, 10); - assert(e == 0); - - uv_sleep(100); // Let the transitions flush - - assert(suspend_calls == 2); - assert(resume_calls == 1); - assert(idle_calls >= 1); - - e = bare_worklet_resume(&worklet); - assert(e == 0); - - e = bare_worklet_suspend(&worklet, 10); - assert(e == 0); - - uv_sleep(100); // Let the transitions flush - - assert(suspend_calls == 3); - assert(resume_calls == 2); - assert(idle_calls >= 2); - - e = bare_worklet_terminate(&worklet); - assert(e == 0); - - bare_worklet_destroy(&worklet); -} diff --git a/test/shared/worklet-suspend-resume.c b/test/shared/worklet-suspend-resume.c deleted file mode 100644 index 913622e..0000000 --- a/test/shared/worklet-suspend-resume.c +++ /dev/null @@ -1,60 +0,0 @@ -#include - -#include "../../shared/worklet.h" - -static bool suspend_called = false; -static bool resume_called = false; - -static void -on_suspend(bare_t *bare, int linger, void *data) { - suspend_called = true; - - assert(linger == 10); -} - -static void -on_resume(bare_t *bare, void *data) { - resume_called = true; -} - -int -main() { - int e; - - bare_worklet_t worklet; - e = bare_worklet_init(&worklet, NULL); - assert(e == 0); - - e = bare_worklet_on_suspend(&worklet, on_suspend, NULL); - assert(e == 0); - - e = bare_worklet_on_resume(&worklet, on_resume, NULL); - assert(e == 0); - - // Keep Bare.IPC open so suspend/resume exercise the queue's ref/unref. - char *code = "BareKit.IPC.on('data', () => {})"; - - uv_buf_t source = uv_buf_init(code, strlen(code)); - - e = bare_worklet_start(&worklet, "app.js", &source, 0, NULL); - assert(e == 0); - - e = bare_worklet_suspend(&worklet, 10); - assert(e == 0); - - uv_sleep(100); // Let suspension flush - - assert(suspend_called); - - e = bare_worklet_resume(&worklet); - assert(e == 0); - - uv_sleep(100); // Let resumption flush - - assert(resume_called); - - e = bare_worklet_terminate(&worklet); - assert(e == 0); - - bare_worklet_destroy(&worklet); -} diff --git a/test/shared/worklet-terminate-after-suspend.c b/test/shared/worklet-terminate-after-suspend.c deleted file mode 100644 index 40bf34b..0000000 --- a/test/shared/worklet-terminate-after-suspend.c +++ /dev/null @@ -1,29 +0,0 @@ -#include - -#include "../../shared/worklet.h" - -int -main() { - int e; - - bare_worklet_t worklet; - e = bare_worklet_init(&worklet, NULL); - assert(e == 0); - - char *code = "console.log('Hello world')"; - - uv_buf_t source = uv_buf_init(code, strlen(code)); - - e = bare_worklet_start(&worklet, "app.js", &source, 0, NULL); - assert(e == 0); - - e = bare_worklet_suspend(&worklet, 0); - assert(e == 0); - - uv_sleep(100); // Let suspension flush - - e = bare_worklet_terminate(&worklet); - assert(e == 0); - - bare_worklet_destroy(&worklet); -} diff --git a/test/shared/worklet-terminate-before-start.c b/test/shared/worklet-terminate-before-start.c deleted file mode 100644 index 00f8431..0000000 --- a/test/shared/worklet-terminate-before-start.c +++ /dev/null @@ -1,57 +0,0 @@ -#include -#include - -#include "../../shared/ipc.h" -#include "../../shared/worklet.h" - -// A worklet that was never started can be suspended, resumed, woken up, -// terminated and pushed to without crashing, and destroying it gives an open ipc -// EOF. - -static void -on_push(bare_worklet_push_t *req, const char *error, const uv_buf_t *reply) { - assert(false); -} - -int -main() { - int e; - - bare_worklet_t worklet; - e = bare_worklet_init(&worklet, NULL); - assert(e == 0); - - bare_ipc_t ipc; - e = bare_ipc_init(&ipc, &worklet); - assert(e == 0); - - e = bare_worklet_suspend(&worklet, 0); - assert(e == 0); - - e = bare_worklet_resume(&worklet); - assert(e == 0); - - e = bare_worklet_wakeup(&worklet, 0); - assert(e == 0); - - e = bare_worklet_terminate(&worklet); - assert(e == 0); - - uv_buf_t payload = uv_buf_init("ping", 4); - - bare_worklet_push_t req; - e = bare_worklet_push(&worklet, &req, &payload, on_push); - assert(e < 0); - - bare_worklet_destroy(&worklet); - - char data[BARE_IPC_READ_BUFFER_SIZE]; - int len; - len = bare_ipc_read(&ipc, data, sizeof(data)); - assert(len == 0); - - e = bare_ipc_write(&ipc, "late", 4); - assert(e == bare_ipc_error); - - bare_ipc_destroy(&ipc); -} diff --git a/test/worklet-addon-dynamic.c b/test/worklet-addon-dynamic.c new file mode 100644 index 0000000..3dd310e --- /dev/null +++ b/test/worklet-addon-dynamic.c @@ -0,0 +1,113 @@ +#include +#include +#include + +#include + +#if defined(_WIN32) +#include +#else +#include +#include +#endif + +// A native addon loaded by the worklet resolves the symbols of Bare from the +// shared library, which the host loads at runtime rather than links. The host +// links nothing of Bare Kit, so the addon can only bind to the library. + +static atomic_bool exited; +static int exit_code; + +static void +on_worklet_exit(int code, void *data) { + exit_code = code; + + atomic_store(&exited, true); +} + +static void * +load(const char *name) { +#if defined(_WIN32) + static HMODULE library = NULL; + + if (library == NULL) library = LoadLibraryA(BARE_KIT); + assert(library != NULL); + + return (void *) GetProcAddress(library, name); +#else + static void *library = NULL; + + if (library == NULL) library = dlopen(BARE_KIT, RTLD_NOW | RTLD_LOCAL); + assert(library != NULL); + + return dlsym(library, name); +#endif +} + +static void +sleep_briefly(void) { +#if defined(_WIN32) + Sleep(10); +#else + usleep(10000); +#endif +} + +int +main() { + int e; + + int (*worklet_create)(const bare_worklet_options_t *, bare_worklet_t **) = load("bare_worklet_create"); + int (*worklet_on_exit)(bare_worklet_t *, bare_worklet_exit_cb, void *) = load("bare_worklet_on_exit"); + int (*worklet_start)(bare_worklet_t *, const char *, const void *, size_t, int, const char *[]) = load("bare_worklet_start"); + void (*worklet_destroy)(bare_worklet_t *) = load("bare_worklet_destroy"); + int (*worklet_teardown)(void) = load("bare_worklet_teardown"); + int (*ipc_create)(bare_worklet_t *, bare_ipc_t **) = load("bare_ipc_create"); + int (*ipc_read)(bare_ipc_t *, void *, size_t) = load("bare_ipc_read"); + void (*ipc_end)(bare_ipc_t *) = load("bare_ipc_end"); + void (*ipc_destroy)(bare_ipc_t *) = load("bare_ipc_destroy"); + + bare_worklet_t *worklet; + e = worklet_create(NULL, &worklet); + assert(e == 0); + + e = worklet_on_exit(worklet, on_worklet_exit, NULL); + assert(e == 0); + + bare_ipc_t *ipc; + e = ipc_create(worklet, &ipc); + assert(e == 0); + + char *code = "Bare.IPC.end(new Bare.Addon(new URL(Bare.argv[0])).exports)"; + + const char *argv[] = {ADDON}; + + e = worklet_start(worklet, "app.js", code, strlen(code), 1, argv); + assert(e == 0); + + char data[BARE_IPC_READ_BUFFER_SIZE]; + size_t received = 0; + int len; + + while ((len = ipc_read(ipc, data + received, sizeof(data) - received)) != 0) { + if (len == bare_ipc_would_block) sleep_briefly(); + else received += len; + } + + assert(received == strlen("Hello from addon")); + assert(memcmp(data, "Hello from addon", received) == 0); + + ipc_end(ipc); + + while (!atomic_load(&exited)) + sleep_briefly(); + + assert(exit_code == 0); + + ipc_destroy(ipc); + + worklet_destroy(worklet); + + e = worklet_teardown(); + assert(e == 0); +} diff --git a/test/worklet-addon.c b/test/worklet-addon.c new file mode 100644 index 0000000..40b2a0e --- /dev/null +++ b/test/worklet-addon.c @@ -0,0 +1,70 @@ +#include +#include +#include + +#include + +// A native addon loaded by the worklet resolves the symbols of Bare from the +// host, which here either links Bare Kit statically and exports its symbols or +// links the shared library. + +static uv_sem_t exited; +static int exit_code; + +static void +on_worklet_exit(int code, void *data) { + exit_code = code; + + uv_sem_post(&exited); +} + +int +main() { + int e; + + e = uv_sem_init(&exited, 0); + assert(e == 0); + + bare_worklet_t *worklet; + e = bare_worklet_create(NULL, &worklet); + assert(e == 0); + + e = bare_worklet_on_exit(worklet, on_worklet_exit, NULL); + assert(e == 0); + + bare_ipc_t *ipc; + e = bare_ipc_create(worklet, &ipc); + assert(e == 0); + + char *code = "Bare.IPC.end(new Bare.Addon(new URL(Bare.argv[0])).exports)"; + + const char *argv[] = {ADDON}; + + e = bare_worklet_start(worklet, "app.js", code, strlen(code), 1, argv); + assert(e == 0); + + char data[BARE_IPC_READ_BUFFER_SIZE]; + size_t received = 0; + int len; + + while ((len = bare_ipc_read(ipc, data + received, sizeof(data) - received)) != 0) { + if (len == bare_ipc_would_block) uv_sleep(10); + else received += len; + } + + assert(received == strlen("Hello from addon")); + assert(memcmp(data, "Hello from addon", received) == 0); + + bare_ipc_end(ipc); + + uv_sem_wait(&exited); + + assert(exit_code == 0); + + bare_ipc_destroy(ipc); + + bare_worklet_destroy(worklet); + + e = bare_worklet_teardown(); + assert(e == 0); +} diff --git a/test/worklet-exit-code.c b/test/worklet-exit-code.c new file mode 100644 index 0000000..49518d9 --- /dev/null +++ b/test/worklet-exit-code.c @@ -0,0 +1,71 @@ +#include +#include +#include + +#include + +// A worklet that exits on its own reports its exit code without being +// terminated or destroyed, by which time its ipc has reached EOF. + +static uv_sem_t exited; +static int exit_code; + +static void +on_worklet_exit(int code, void *data) { + char buffer[BARE_IPC_READ_BUFFER_SIZE]; + + int len = bare_ipc_read((bare_ipc_t *) data, buffer, sizeof(buffer)); + assert(len == 0); + + exit_code = code; + + uv_sem_post(&exited); +} + +int +main() { + int e; + + e = uv_sem_init(&exited, 0); + assert(e == 0); + + bare_worklet_t *worklet; + e = bare_worklet_create(NULL, &worklet); + assert(e == 0); + + bare_ipc_t *ipc; + e = bare_ipc_create(worklet, &ipc); + assert(e == 0); + + e = bare_worklet_on_exit(worklet, on_worklet_exit, ipc); + assert(e == 0); + + char *code = "setTimeout(() => Bare.exit(42), 50)"; + + e = bare_worklet_start(worklet, "app.js", code, strlen(code), 0, NULL); + assert(e == 0); + + uv_sem_wait(&exited); + + assert(exit_code == 42); + + // Once it has torn down, the worklet ignores the host. + e = bare_worklet_suspend(worklet, 0); + assert(e == 0); + + e = bare_worklet_resume(worklet); + assert(e == 0); + + e = bare_worklet_wakeup(worklet, 0); + assert(e == 0); + + e = bare_worklet_terminate(worklet); + assert(e == 0); + + bare_ipc_destroy(ipc); + + bare_worklet_destroy(worklet); + + e = bare_worklet_teardown(); + assert(e == 0); +} diff --git a/test/worklet-ipc-after-destroy.c b/test/worklet-ipc-after-destroy.c new file mode 100644 index 0000000..ae47412 --- /dev/null +++ b/test/worklet-ipc-after-destroy.c @@ -0,0 +1,45 @@ +#include +#include +#include + +#include + +// An ipc outlives its worklet: once the worklet is destroyed, it reads EOF and +// fails writes without touching the worklet again. + +int +main() { + int e; + + bare_worklet_t *worklet; + e = bare_worklet_create(NULL, &worklet); + assert(e == 0); + + char *code = "Bare.IPC.on('data', () => {})"; + + e = bare_worklet_start(worklet, "app.js", code, strlen(code), 0, NULL); + assert(e == 0); + + bare_ipc_t *ipc; + e = bare_ipc_create(worklet, &ipc); + assert(e == 0); + + bare_worklet_destroy(worklet); + + char data[BARE_IPC_READ_BUFFER_SIZE]; + int len; + + while ((len = bare_ipc_read(ipc, data, sizeof(data))) != 0) { + assert(len > 0 || len == bare_ipc_would_block); + + uv_sleep(10); + } + + e = bare_ipc_write(ipc, "late", 4); + assert(e == bare_ipc_error); + + bare_ipc_destroy(ipc); + + e = bare_worklet_teardown(); + assert(e == 0); +} diff --git a/test/shared/worklet-ipc-destroy-in-callback.c b/test/worklet-ipc-destroy-in-callback.c similarity index 58% rename from test/shared/worklet-ipc-destroy-in-callback.c rename to test/worklet-ipc-destroy-in-callback.c index 462e5cd..9d63887 100644 --- a/test/shared/worklet-ipc-destroy-in-callback.c +++ b/test/worklet-ipc-destroy-in-callback.c @@ -2,26 +2,25 @@ #include #include -#include "../../shared/ipc.h" -#include "../../shared/worklet.h" +#include // An ipc may be destroyed from its own poll callback. static uv_async_t finished; -static bare_ipc_t ipc; -static bare_ipc_poll_t poll; +static bare_ipc_t *ipc; +static bare_ipc_poll_t *poll; static void on_poll(bare_ipc_poll_t *poll, int events) { char data[BARE_IPC_READ_BUFFER_SIZE]; - int len = bare_ipc_read(&ipc, data, sizeof(data)); + int len = bare_ipc_read(ipc, data, sizeof(data)); if (len == bare_ipc_would_block) return; bare_ipc_poll_destroy(poll); - bare_ipc_destroy(&ipc); + bare_ipc_destroy(ipc); uv_async_send(&finished); } @@ -40,28 +39,29 @@ main() { e = uv_async_init(loop, &finished, on_finished); assert(e == 0); - bare_worklet_t worklet; - e = bare_worklet_init(&worklet, NULL); + bare_worklet_t *worklet; + e = bare_worklet_create(NULL, &worklet); assert(e == 0); char *code = "Bare.IPC.write('Hello!')"; - uv_buf_t source = uv_buf_init(code, strlen(code)); - - e = bare_worklet_start(&worklet, "app.js", &source, 0, NULL); + e = bare_worklet_start(worklet, "app.js", code, strlen(code), 0, NULL); assert(e == 0); - e = bare_ipc_init(&ipc, &worklet); + e = bare_ipc_create(worklet, &ipc); assert(e == 0); - e = bare_ipc_poll_init(&poll, &ipc); + e = bare_ipc_poll_create(ipc, &poll); assert(e == 0); - e = bare_ipc_poll_start(&poll, bare_ipc_readable, on_poll); + e = bare_ipc_poll_start(poll, bare_ipc_readable, on_poll); assert(e == 0); e = uv_run(loop, UV_RUN_DEFAULT); assert(e == 0); - bare_worklet_destroy(&worklet); + bare_worklet_destroy(worklet); + + e = bare_worklet_teardown(); + assert(e == 0); } diff --git a/test/worklet-ipc-exit.c b/test/worklet-ipc-exit.c new file mode 100644 index 0000000..859d5d7 --- /dev/null +++ b/test/worklet-ipc-exit.c @@ -0,0 +1,67 @@ +#include +#include +#include + +#include + +// A worklet whose ipc has ended in both directions exits on its own, without +// being terminated or destroyed. + +static uv_sem_t exited; +static int exit_code; + +static void +on_worklet_exit(int code, void *data) { + exit_code = code; + + uv_sem_post(&exited); +} + +int +main() { + int e; + + e = uv_sem_init(&exited, 0); + assert(e == 0); + + bare_worklet_t *worklet; + e = bare_worklet_create(NULL, &worklet); + assert(e == 0); + + e = bare_worklet_on_exit(worklet, on_worklet_exit, NULL); + assert(e == 0); + + bare_ipc_t *ipc; + e = bare_ipc_create(worklet, &ipc); + assert(e == 0); + + char *code = "Bare.IPC.on('data', (data) => Bare.IPC.end(data))"; + + e = bare_worklet_start(worklet, "app.js", code, strlen(code), 0, NULL); + assert(e == 0); + + e = bare_ipc_write(ipc, "ping", 4); + assert(e == 4); + + char data[BARE_IPC_READ_BUFFER_SIZE]; + int len; + + while ((len = bare_ipc_read(ipc, data, sizeof(data))) != 0) { + assert(len > 0 || len == bare_ipc_would_block); + + uv_sleep(10); + } + + bare_ipc_close(ipc); + + uv_sem_wait(&exited); + + assert(exit_code == 0); + + bare_ipc_destroy(ipc); + + bare_worklet_destroy(worklet); + + e = bare_worklet_teardown(); + assert(e == 0); +} diff --git a/test/worklet-ipc-half-close.c b/test/worklet-ipc-half-close.c new file mode 100644 index 0000000..40860bc --- /dev/null +++ b/test/worklet-ipc-half-close.c @@ -0,0 +1,67 @@ +#include +#include +#include + +#include + +// Ending Bare.IPC from the worklet is a half-close: the host reads EOF but may +// keep writing. + +static uv_sem_t exited; +static int exit_code; + +static void +on_worklet_exit(int code, void *data) { + exit_code = code; + + uv_sem_post(&exited); +} + +int +main() { + int e; + + e = uv_sem_init(&exited, 0); + assert(e == 0); + + bare_worklet_t *worklet; + e = bare_worklet_create(NULL, &worklet); + assert(e == 0); + + e = bare_worklet_on_exit(worklet, on_worklet_exit, NULL); + assert(e == 0); + + char *code = + "Bare.IPC.on('data', (data) => Bare.exit(data.toString() === 'hello' ? 0 : 1))\n" + "Bare.IPC.end()\n"; + + e = bare_worklet_start(worklet, "app.js", code, strlen(code), 0, NULL); + assert(e == 0); + + bare_ipc_t *ipc; + e = bare_ipc_create(worklet, &ipc); + assert(e == 0); + + char data[BARE_IPC_READ_BUFFER_SIZE]; + int len; + + while ((len = bare_ipc_read(ipc, data, sizeof(data))) != 0) { + assert(len > 0 || len == bare_ipc_would_block); + + uv_sleep(10); + } + + e = bare_ipc_write(ipc, "hello", 5); + assert(e == 5); + + uv_sem_wait(&exited); + + assert(exit_code == 0); + + bare_ipc_destroy(ipc); + + bare_worklet_destroy(worklet); + + e = bare_worklet_teardown(); + assert(e == 0); +} diff --git a/test/worklet-ipc-host-end.c b/test/worklet-ipc-host-end.c new file mode 100644 index 0000000..844abeb --- /dev/null +++ b/test/worklet-ipc-host-end.c @@ -0,0 +1,78 @@ +#include +#include +#include + +#include + +// Ending the host end is a half-close: Bare.IPC reads EOF while the host keeps +// reading, and the worklet exits once it ends its own end in turn. + +static uv_sem_t exited; +static int exit_code; + +static void +on_worklet_exit(int code, void *data) { + exit_code = code; + + uv_sem_post(&exited); +} + +int +main() { + int e; + + e = uv_sem_init(&exited, 0); + assert(e == 0); + + bare_worklet_t *worklet; + e = bare_worklet_create(NULL, &worklet); + assert(e == 0); + + e = bare_worklet_on_exit(worklet, on_worklet_exit, NULL); + assert(e == 0); + + char *code = + "const chunks = []\n" + "Bare.IPC\n" + " .on('data', (data) => chunks.push(data))\n" + " .on('end', () => Bare.IPC.end(Buffer.concat(chunks)))\n"; + + e = bare_worklet_start(worklet, "app.js", code, strlen(code), 0, NULL); + assert(e == 0); + + bare_ipc_t *ipc; + e = bare_ipc_create(worklet, &ipc); + assert(e == 0); + + e = bare_ipc_write(ipc, "hello", 5); + assert(e == 5); + + bare_ipc_end(ipc); + bare_ipc_end(ipc); + + e = bare_ipc_write(ipc, "world", 5); + assert(e == bare_ipc_error); + + char data[BARE_IPC_READ_BUFFER_SIZE]; + size_t received = 0; + int len; + + while ((len = bare_ipc_read(ipc, data + received, sizeof(data) - received)) != 0) { + if (len == bare_ipc_would_block) uv_sleep(10); + else received += len; + } + + assert(received == 5); + assert(memcmp(data, "hello", 5) == 0); + + uv_sem_wait(&exited); + + assert(exit_code == 0); + + bare_ipc_destroy(ipc); + + bare_worklet_destroy(worklet); + + e = bare_worklet_teardown(); + assert(e == 0); +} diff --git a/test/worklet-ipc-short-read.c b/test/worklet-ipc-short-read.c new file mode 100644 index 0000000..29d2bbb --- /dev/null +++ b/test/worklet-ipc-short-read.c @@ -0,0 +1,49 @@ +#include +#include +#include + +#include + +// A message larger than the read buffer arrives over several reads. + +int +main() { + int e; + + bare_worklet_t *worklet; + e = bare_worklet_create(NULL, &worklet); + assert(e == 0); + + char *code = "Bare.IPC.write('Hello world!')"; + + e = bare_worklet_start(worklet, "app.js", code, strlen(code), 0, NULL); + assert(e == 0); + + bare_ipc_t *ipc; + e = bare_ipc_create(worklet, &ipc); + assert(e == 0); + + char message[64]; + size_t received = 0; + + while (received < 12) { + int len = bare_ipc_read(ipc, message + received, 5); + + if (len == bare_ipc_would_block) { + uv_sleep(10); + } else { + assert(len > 0 && len <= 5); + + received += len; + } + } + + assert(memcmp(message, "Hello world!", 12) == 0); + + bare_ipc_destroy(ipc); + + bare_worklet_destroy(worklet); + + e = bare_worklet_teardown(); + assert(e == 0); +} diff --git a/test/worklet-ipc-single.c b/test/worklet-ipc-single.c new file mode 100644 index 0000000..c83206f --- /dev/null +++ b/test/worklet-ipc-single.c @@ -0,0 +1,35 @@ +#include +#include + +#include + +// A second ipc on the same worklet is refused. + +int +main() { + int e; + + bare_worklet_t *worklet; + e = bare_worklet_create(NULL, &worklet); + assert(e == 0); + + char *code = "Bare.IPC.on('data', () => {})"; + + e = bare_worklet_start(worklet, "app.js", code, strlen(code), 0, NULL); + assert(e == 0); + + bare_ipc_t *ipc; + e = bare_ipc_create(worklet, &ipc); + assert(e == 0); + + bare_ipc_t *other; + e = bare_ipc_create(worklet, &other); + assert(e < 0); + + bare_ipc_destroy(ipc); + + bare_worklet_destroy(worklet); + + e = bare_worklet_teardown(); + assert(e == 0); +} diff --git a/test/worklet-ipc-write-after-close.c b/test/worklet-ipc-write-after-close.c new file mode 100644 index 0000000..4dd160d --- /dev/null +++ b/test/worklet-ipc-write-after-close.c @@ -0,0 +1,57 @@ +#include +#include +#include + +#include + +// A pending worklet write must error, not hang, once the host closes its ipc. + +static uv_sem_t exited; +static int exit_code; + +static void +on_worklet_exit(int code, void *data) { + exit_code = code; + + uv_sem_post(&exited); +} + +int +main() { + int e; + + e = uv_sem_init(&exited, 0); + assert(e == 0); + + bare_worklet_t *worklet; + e = bare_worklet_create(NULL, &worklet); + assert(e == 0); + + e = bare_worklet_on_exit(worklet, on_worklet_exit, NULL); + assert(e == 0); + + char *code = + "Bare.IPC.on('error', () => Bare.exit(0))\n" + "setInterval(() => Bare.IPC.write(Buffer.alloc(64)), 5)\n"; + + e = bare_worklet_start(worklet, "app.js", code, strlen(code), 0, NULL); + assert(e == 0); + + bare_ipc_t *ipc; + e = bare_ipc_create(worklet, &ipc); + assert(e == 0); + + // Never read, so the queue fills and the worklet is left with a pending write. + uv_sleep(100); + + bare_ipc_destroy(ipc); + + uv_sem_wait(&exited); + + assert(exit_code == 0); + + bare_worklet_destroy(worklet); + + e = bare_worklet_teardown(); + assert(e == 0); +} diff --git a/test/worklet-ipc.c b/test/worklet-ipc.c new file mode 100644 index 0000000..71a35cc --- /dev/null +++ b/test/worklet-ipc.c @@ -0,0 +1,107 @@ +#include +#include +#include + +#include + +// Polls for both events to echo a write much larger than the queue through the +// worklet. + +#define LEN (4 * 1024 * 1024) + +static char message[LEN]; + +static size_t written = 0; +static size_t received = 0; + +static uv_async_t finished; + +static void +on_poll(bare_ipc_poll_t *poll, int events) { + int e; + + bare_ipc_t *ipc = bare_ipc_poll_get_ipc(poll); + + while (written < LEN) { + int len = bare_ipc_write(ipc, &message[written], LEN - written); + if (len == bare_ipc_would_block) break; + assert(len > 0); + + written += len; + } + + while (received < LEN) { + char data[BARE_IPC_READ_BUFFER_SIZE]; + + int len = bare_ipc_read(ipc, data, sizeof(data)); + if (len == bare_ipc_would_block) break; + assert(len > 0); + + assert(memcmp(data, &message[received], len) == 0); + + received += len; + } + + if (received == LEN) { + e = bare_ipc_poll_stop(poll); + assert(e == 0); + + uv_async_send(&finished); + } else { + e = bare_ipc_poll_start(poll, written < LEN ? bare_ipc_readable | bare_ipc_writable : bare_ipc_readable, on_poll); + assert(e == 0); + } +} + +static void +on_finished(uv_async_t *handle) { + uv_close((uv_handle_t *) handle, NULL); +} + +int +main() { + int e; + + for (size_t i = 0; i < LEN; i++) + message[i] = (char) i; + + uv_loop_t *loop = uv_default_loop(); + + e = uv_async_init(loop, &finished, on_finished); + assert(e == 0); + + bare_worklet_t *worklet; + e = bare_worklet_create(NULL, &worklet); + assert(e == 0); + + char *code = "Bare.IPC.on('data', (data) => Bare.IPC.write(data))"; + + e = bare_worklet_start(worklet, "app.js", code, strlen(code), 0, NULL); + assert(e == 0); + + bare_ipc_t *ipc; + e = bare_ipc_create(worklet, &ipc); + assert(e == 0); + + bare_ipc_poll_t *poll; + e = bare_ipc_poll_create(ipc, &poll); + assert(e == 0); + + e = bare_ipc_poll_start(poll, bare_ipc_readable | bare_ipc_writable, on_poll); + assert(e == 0); + + e = uv_run(loop, UV_RUN_DEFAULT); + assert(e == 0); + + bare_ipc_poll_destroy(poll); + + bare_ipc_destroy(ipc); + + bare_worklet_destroy(worklet); + + e = bare_worklet_teardown(); + assert(e == 0); + + e = uv_loop_close(loop); + assert(e == 0); +} diff --git a/test/worklet-suspend-resume.c b/test/worklet-suspend-resume.c new file mode 100644 index 0000000..d0b67aa --- /dev/null +++ b/test/worklet-suspend-resume.c @@ -0,0 +1,73 @@ +#include +#include +#include + +#include + +// The open ipc keeps the worklet alive until a suspension unrefs it, so each +// suspension idles and each resumption refs it again. + +static int suspends = 0; +static int idles = 0; +static int resumes = 0; + +static void +on_suspend(int linger, void *data) { + assert(linger == 10); + + suspends++; +} + +static void +on_idle(void *data) { + idles++; +} + +static void +on_resume(void *data) { + resumes++; +} + +int +main() { + int e; + + bare_worklet_t *worklet; + e = bare_worklet_create(NULL, &worklet); + assert(e == 0); + + e = bare_worklet_on_suspend(worklet, on_suspend, NULL); + assert(e == 0); + + e = bare_worklet_on_idle(worklet, on_idle, NULL); + assert(e == 0); + + e = bare_worklet_on_resume(worklet, on_resume, NULL); + assert(e == 0); + + char *code = "Bare.IPC.on('data', () => {})"; + + e = bare_worklet_start(worklet, "app.js", code, strlen(code), 0, NULL); + assert(e == 0); + + for (int i = 1; i <= 3; i++) { + if (i > 1) { + e = bare_worklet_resume(worklet); + assert(e == 0); + } + + e = bare_worklet_suspend(worklet, 10); + assert(e == 0); + + uv_sleep(100); + + assert(suspends == i); + assert(resumes == i - 1); + assert(idles >= i); + } + + bare_worklet_destroy(worklet); + + e = bare_worklet_teardown(); + assert(e == 0); +} diff --git a/test/worklet-teardown.c b/test/worklet-teardown.c new file mode 100644 index 0000000..e944f7a --- /dev/null +++ b/test/worklet-teardown.c @@ -0,0 +1,50 @@ +#include +#include +#include + +#include + +// Destroying a running worklet still reports its exit, once, and the exit +// callback may release the host's resources. Tearing down waits for it, after +// which no worklet may start. + +static int exits = 0; + +static void +on_worklet_exit(int code, void *data) { + free(data); + + exits++; +} + +int +main() { + int e; + + bare_worklet_t *worklet; + e = bare_worklet_create(NULL, &worklet); + assert(e == 0); + + e = bare_worklet_on_exit(worklet, on_worklet_exit, malloc(1)); + assert(e == 0); + + char *code = "setInterval(() => {}, 1000)"; + + e = bare_worklet_start(worklet, "app.js", code, strlen(code), 0, NULL); + assert(e == 0); + + bare_worklet_destroy(worklet); + + e = bare_worklet_teardown(); + assert(e == 0); + + assert(exits == 1); + + e = bare_worklet_create(NULL, &worklet); + assert(e == 0); + + e = bare_worklet_start(worklet, "app.js", code, strlen(code), 0, NULL); + assert(e < 0); + + bare_worklet_destroy(worklet); +} diff --git a/test/worklet-terminate-before-start.c b/test/worklet-terminate-before-start.c new file mode 100644 index 0000000..60a4e9a --- /dev/null +++ b/test/worklet-terminate-before-start.c @@ -0,0 +1,46 @@ +#include + +#include + +// A worklet that was never started can be suspended, resumed, woken up and +// terminated without crashing, and destroying it gives an open ipc EOF. + +int +main() { + int e; + + bare_worklet_t *worklet; + e = bare_worklet_create(NULL, &worklet); + assert(e == 0); + + bare_ipc_t *ipc; + e = bare_ipc_create(worklet, &ipc); + assert(e == 0); + + e = bare_worklet_suspend(worklet, 0); + assert(e == 0); + + e = bare_worklet_resume(worklet); + assert(e == 0); + + e = bare_worklet_wakeup(worklet, 0); + assert(e == 0); + + e = bare_worklet_terminate(worklet); + assert(e == 0); + + bare_worklet_destroy(worklet); + + char data[BARE_IPC_READ_BUFFER_SIZE]; + int len; + len = bare_ipc_read(ipc, data, sizeof(data)); + assert(len == 0); + + e = bare_ipc_write(ipc, "late", 4); + assert(e == bare_ipc_error); + + bare_ipc_destroy(ipc); + + e = bare_worklet_teardown(); + assert(e == 0); +} diff --git a/win32/CMakeLists.txt b/win32/CMakeLists.txt deleted file mode 100644 index a57bdea..0000000 --- a/win32/CMakeLists.txt +++ /dev/null @@ -1,51 +0,0 @@ -add_library(bare_kit SHARED) - -set_target_properties( - bare_kit - PROPERTIES - C_STANDARD 11 - POSITION_INDEPENDENT_CODE ON - OUTPUT_NAME bare-kit -) - -target_sources( - bare_kit - PUBLIC - ipc.def - worklet.def -) - -target_link_libraries( - bare_kit - PRIVATE - bare_worklet -) - -# A prebuilt addon delay-loads `bare.dll` and resolves it against the host -# executable, so a host embedding the runtime here has to re-export these -# symbols for any addon to load. Ship the forwarders next to the library so that -# a host passes `/DEF:` at this file instead of deriving the list itself. -set(exports - "${bare}/src/bare.def" - "${bare}/src/js.def" - "${bare}/src/napi.def" - "${bare}/src/uv.def" - "${CMAKE_CURRENT_LIST_DIR}/ipc.def" - "${CMAKE_CURRENT_LIST_DIR}/worklet.def" -) - -set(forwarders "EXPORTS\n") - -foreach(export ${exports}) - file(STRINGS "${export}" symbols) - - foreach(symbol ${symbols}) - string(STRIP "${symbol}" symbol) - - if(symbol MATCHES "^[A-Za-z_][A-Za-z0-9_]*$" AND NOT symbol STREQUAL "EXPORTS") - string(APPEND forwarders "\t${symbol} = bare-kit.${symbol}\n") - endif() - endforeach() -endforeach() - -file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/bare-kit.def" CONTENT "${forwarders}") diff --git a/win32/ipc.def b/win32/ipc.def deleted file mode 100644 index 6a38226..0000000 --- a/win32/ipc.def +++ /dev/null @@ -1,15 +0,0 @@ -EXPORTS - bare_ipc_alloc - bare_ipc_init - bare_ipc_close - bare_ipc_destroy - bare_ipc_read - bare_ipc_write - bare_ipc_poll_alloc - bare_ipc_poll_init - bare_ipc_poll_destroy - bare_ipc_poll_get_data - bare_ipc_poll_set_data - bare_ipc_poll_get_ipc - bare_ipc_poll_start - bare_ipc_poll_stop diff --git a/win32/worklet.def b/win32/worklet.def deleted file mode 100644 index 72eba5c..0000000 --- a/win32/worklet.def +++ /dev/null @@ -1,19 +0,0 @@ -EXPORTS - bare_worklet_optimize_for_memory - bare_worklet_alloc - bare_worklet_init - bare_worklet_destroy - bare_worklet_on_suspend - bare_worklet_on_wakeup - bare_worklet_on_idle - bare_worklet_on_resume - bare_worklet_get_data - bare_worklet_set_data - bare_worklet_start - bare_worklet_suspend - bare_worklet_resume - bare_worklet_wakeup - bare_worklet_terminate - bare_worklet_push - bare_worklet_push_get_data - bare_worklet_push_set_data