diff --git a/.vscode/launch.json b/.vscode/launch.json index 5bfff0be2caf..940b85848c30 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -342,7 +342,6 @@ "trace": "Off", "setupCommands": [ "handle SIGPWR nostop noprint pass", - "source ${workspaceFolder}/misctools/gdb/std_gdb_pretty_printers.py", "set substitute-path /webkitbuild/vendor/WebKit ${workspaceFolder}/vendor/WebKit", "set substitute-path /webkitbuild/.WTF/Headers ${workspaceFolder}/vendor/WebKit/Source/WTF", // uncomment if you like diff --git a/hawk.toml b/hawk.toml index eae96fd1d4f7..a7522a1de5f4 100644 --- a/hawk.toml +++ b/hawk.toml @@ -452,54 +452,6 @@ kind = "enum_variant" level = "expect" reason = "external code table: weak-ref type numbering shared with JSC" -[[override]] -lint = "hawk::dead_public" -crate = "bun_platform" -item = "darwin::Category::PointsOfInterest" -kind = "enum_variant" -level = "expect" -reason = "external code table: OSLog signpost category values" - -[[override]] -lint = "hawk::dead_public" -crate = "bun_platform" -item = "darwin::Category::Dynamicity" -kind = "enum_variant" -level = "expect" -reason = "external code table: OSLog signpost category values" - -[[override]] -lint = "hawk::dead_public" -crate = "bun_platform" -item = "darwin::Category::SizeAndThroughput" -kind = "enum_variant" -level = "expect" -reason = "external code table: OSLog signpost category values" - -[[override]] -lint = "hawk::dead_public" -crate = "bun_platform" -item = "darwin::Category::TimeProfile" -kind = "enum_variant" -level = "expect" -reason = "external code table: OSLog signpost category values" - -[[override]] -lint = "hawk::dead_public" -crate = "bun_platform" -item = "darwin::Category::SystemReporting" -kind = "enum_variant" -level = "expect" -reason = "external code table: OSLog signpost category values" - -[[override]] -lint = "hawk::dead_public" -crate = "bun_platform" -item = "darwin::Category::UserCustom" -kind = "enum_variant" -level = "expect" -reason = "external code table: OSLog signpost category values" - [[override]] lint = "hawk::dead_public" crate = "bun_runtime" diff --git a/meta.json b/meta.json deleted file mode 100644 index 682daccfce46..000000000000 --- a/meta.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "inputs": { - "../../tmp/test-entry.js": { - "bytes": 21, - "imports": [ - ], - "format": "esm" - } - }, - "outputs": { - "./test-entry.js": { - "bytes": 49, - "inputs": { - "../../tmp/test-entry.js": { - "bytesInOutput": 22 - } - }, - "imports": [ - ], - "exports": [], - "entryPoint": "../../tmp/test-entry.js" - } - } -} diff --git a/misctools/.gitignore b/misctools/.gitignore deleted file mode 100644 index 247e7e6e79f8..000000000000 --- a/misctools/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -*.tgz -tgz -readlink-getfd -readlink-realpath -http_bench -httpbench -fetch -tgz2hop -hop -bun.lockb diff --git a/misctools/gdb/std_gdb_pretty_printers.py b/misctools/gdb/std_gdb_pretty_printers.py deleted file mode 100644 index a564de7c1842..000000000000 --- a/misctools/gdb/std_gdb_pretty_printers.py +++ /dev/null @@ -1,142 +0,0 @@ -# pretty printing for the standard library. -# put "source /path/to/stage2_gdb_pretty_printers.py" in ~/.gdbinit to load it automatically. -import re -import gdb.printing - -# Handles both ArrayList and ArrayListUnmanaged. -class ArrayListPrinter: - def __init__(self, val): - self.val = val - - def to_string(self): - type = self.val.type.name[len('std.array_list.'):] - type = re.sub(r'^ArrayListAligned(Unmanaged)?\((.*),null\)$', r'ArrayList\1(\2)', type) - return '%s of length %s, capacity %s' % (type, self.val['items']['len'], self.val['capacity']) - - def children(self): - for i in range(self.val['items']['len']): - item = self.val['items']['ptr'] + i - yield ('[%d]' % i, item.dereference()) - - def display_hint(self): - return 'array' - -class MultiArrayListPrinter: - def __init__(self, val): - self.val = val - - def child_type(self): - (helper_fn, _) = gdb.lookup_symbol('%s.dbHelper' % self.val.type.name) - return helper_fn.type.fields()[1].type.target() - - def to_string(self): - type = self.val.type.name[len('std.multi_array_list.'):] - return '%s of length %s, capacity %s' % (type, self.val['len'], self.val['capacity']) - - def slice(self): - fields = self.child_type().fields() - base = self.val['bytes'] - cap = self.val['capacity'] - len = self.val['len'] - - if len == 0: - return - - fields = sorted(fields, key=lambda field: field.type.alignof, reverse=True) - - for field in fields: - ptr = base.cast(field.type.pointer()).dereference().cast(field.type.array(len - 1)) - base += field.type.sizeof * cap - yield (field.name, ptr) - - def children(self): - for i, (name, ptr) in enumerate(self.slice()): - yield ('[%d]' % i, name) - yield ('[%d]' % i, ptr) - - def display_hint(self): - return 'map' - -# Handles both HashMap and HashMapUnmanaged. -class HashMapPrinter: - def __init__(self, val): - self.type = val.type - is_managed = re.search(r'^std\.hash_map\.HashMap\(', self.type.name) - self.val = val['unmanaged'] if is_managed else val - - def header_ptr_type(self): - (helper_fn, _) = gdb.lookup_symbol('%s.dbHelper' % self.val.type.name) - return helper_fn.type.fields()[1].type - - def header(self): - if self.val['metadata'] == 0: - return None - return (self.val['metadata'].cast(self.header_ptr_type()) - 1).dereference() - - def to_string(self): - type = self.type.name[len('std.hash_map.'):] - type = re.sub(r'^HashMap(Unmanaged)?\((.*),std.hash_map.AutoContext\(.*$', r'AutoHashMap\1(\2)', type) - hdr = self.header() - if hdr is not None: - cap = hdr['capacity'] - else: - cap = 0 - return '%s of length %s, capacity %s' % (type, self.val['size'], cap) - - def children(self): - hdr = self.header() - if hdr is None: - return - is_map = self.display_hint() == 'map' - for i in range(hdr['capacity']): - metadata = self.val['metadata'] + i - if metadata.dereference()['used'] == 1: - yield ('[%d]' % i, (hdr['keys'] + i).dereference()) - if is_map: - yield ('[%d]' % i, (hdr['values'] + i).dereference()) - - def display_hint(self): - for field in self.header_ptr_type().target().fields(): - if field.name == 'values': - return 'map' - return 'array' - -# Handles both ArrayHashMap and ArrayHashMapUnmanaged. -class ArrayHashMapPrinter: - def __init__(self, val): - self.type = val.type - is_managed = re.search(r'^std\.array_hash_map\.ArrayHashMap\(', self.type.name) - self.val = val['unmanaged'] if is_managed else val - - def to_string(self): - type = self.type.name[len('std.array_hash_map.'):] - type = re.sub(r'^ArrayHashMap(Unmanaged)?\((.*),std.array_hash_map.AutoContext\(.*$', r'AutoArrayHashMap\1(\2)', type) - return '%s of length %s' % (type, self.val['entries']['len']) - - def children(self): - entries = MultiArrayListPrinter(self.val['entries']) - len = self.val['entries']['len'] - fields = {} - for name, ptr in entries.slice(): - fields[str(name)] = ptr - - for i in range(len): - if 'key' in fields: - yield ('[%d]' % i, fields['key'][i]) - else: - yield ('[%d]' % i, '{}') - if 'value' in fields: - yield ('[%d]' % i, fields['value'][i]) - - def display_hint(self): - for name, ptr in MultiArrayListPrinter(self.val['entries']).slice(): - if name == 'value': - return 'map' - return 'array' - -pp = gdb.printing.RegexpCollectionPrettyPrinter('Zig standard library') -pp.add_printer('ArrayList', r'^std\.array_list\.ArrayListAligned(Unmanaged)?\(.*\)$', ArrayListPrinter) -pp.add_printer('MultiArrayList', r'^std\.multi_array_list\.MultiArrayList\(.*\)$', MultiArrayListPrinter) -pp.add_printer('HashMap', r'^std\.hash_map\.HashMap(Unmanaged)?\(.*\)$', HashMapPrinter) -pp.add_printer('ArrayHashMap', r'^std\.array_hash_map\.ArrayHashMap(Unmanaged)?\(.*\)$', ArrayHashMapPrinter) -gdb.printing.register_pretty_printer(gdb.current_objfile(), pp) diff --git a/misctools/mime.js b/misctools/mime.js deleted file mode 100644 index ea95f11251a0..000000000000 --- a/misctools/mime.js +++ /dev/null @@ -1,46 +0,0 @@ -const json = await (await fetch("https://raw.githubusercontent.com/jshttp/mime-db/master/db.json")).json(); - -json["application/javascript"].extensions.push(`ts`, `tsx`, `mts`, `mtsx`, `cts`, `cjs`, `mjs`, `js`); - -delete json["application/node"]; -delete json["application/deno"]; -delete json["application/wasm"]; - -var categories = new Set(); -var all = "pub const all = struct {"; -for (let key of Object.keys(json).sort()) { - const [category] = key.split("/"); - categories.add(category); - all += `pub const @"${key}": MimeType = MimeType{.category = .@"${category}", .value = "${key}"};\n`; -} - -const withExtensions = [ - ...new Set( - Object.keys(json) - .filter(key => { - return !!json[key]?.extensions?.length; - }) - .flatMap(mime => { - return [...new Set(json[mime].extensions)].map(ext => { - return [`.{.@"${ext}", all.@"${mime}"}`]; - }); - }) - .sort(), - ), -]; - -all += "\n"; - -all += ` pub const extensions = ComptimeStringMap(MimeType, .{ -${withExtensions.join(",\n")}, -}); -};`; - -all += "\n"; - -// all += `pub const Category = enum { -// ${[...categories].map((a) => `@"${a}"`).join(", \n")} -// }; -// `; - -console.log(all); diff --git a/packages/bun-release/scripts/npm-exec.ts b/packages/bun-release/scripts/npm-exec.ts deleted file mode 100644 index c8a9f4aeab0f..000000000000 --- a/packages/bun-release/scripts/npm-exec.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { execFileSync } from "child_process"; -import { importBun } from "../src/npm/install"; - -importBun() - .then(bun => { - return execFileSync(bun, process.argv.slice(2), { - stdio: "inherit", - }); - }) - .catch(error => { - console.error(error); - process.exit(1); - }); diff --git a/packages/bun-usockets/misc/gen_test_certs.sh b/packages/bun-usockets/misc/gen_test_certs.sh deleted file mode 100755 index 01343f640e0e..000000000000 --- a/packages/bun-usockets/misc/gen_test_certs.sh +++ /dev/null @@ -1,51 +0,0 @@ -#!/bin/bash - -set -eo pipefail - -function gen_cert { - local path=$1 - local CN=$2 - local ca_path=$3 - local ca_name=${4:-ca} - - mkdir -p ${path} - - openssl genrsa -out ${path}/${CN}_key.pem 2048 >/dev/null - echo "generated ${path}/${CN}_key.pem" - - openssl req -new -sha256 \ - -key ${path}/${CN}_key.pem \ - -subj "/O=uNetworking/O=uSockets/CN=${CN}" \ - -reqexts SAN \ - -config <(cat /etc/ssl/openssl.cnf \ - <(printf "\n[SAN]\nsubjectAltName=DNS:localhost,DNS:127.0.0.1")) \ - -out ${path}/${CN}.csr &>/dev/null - - if [ -z "${ca_path}" ]; then - # self-signed - openssl x509 -req -in ${path}/${CN}.csr \ - -signkey ${path}/${CN}_key.pem -days 365 -sha256 \ - -outform PEM -out ${path}/${CN}_crt.pem &>/dev/null - - else - openssl x509 -req -in ${path}/${CN}.csr \ - -CA ${ca_path}/${ca_name}_crt.pem -CAkey ${ca_path}/${ca_name}_key.pem \ - -CAcreateserial -days 365 -sha256 \ - -outform PEM -out ${path}/${CN}_crt.pem &>/dev/null - fi - - rm -f ${path}/${CN}.csr - echo "generated ${path}/${CN}_crt.pem" -} - -# main -certs=${1:-"/tmp/certs"} - -gen_cert "${certs}" "valid_ca" -gen_cert "${certs}" "valid_server" "${certs}" "valid_ca" -gen_cert "${certs}" "valid_client" "${certs}" "valid_ca" - -gen_cert "${certs}" "invalid_ca" -gen_cert "${certs}" "invalid_client" "${certs}" "invalid_ca" -gen_cert "${certs}" "selfsigned_client" - diff --git a/packages/bun-usockets/misc/layout.png b/packages/bun-usockets/misc/layout.png deleted file mode 100644 index e8dd1b0b0770..000000000000 Binary files a/packages/bun-usockets/misc/layout.png and /dev/null differ diff --git a/packages/bun-usockets/misc/manual.md b/packages/bun-usockets/misc/manual.md deleted file mode 100644 index 275d1f815168..000000000000 --- a/packages/bun-usockets/misc/manual.md +++ /dev/null @@ -1,180 +0,0 @@ -# libusockets.h - -This is the only header you include. Following documentation has been extracted from this header. It may be outdated, go read the header directly for up-to-date documentation. - -These interfaces are "beta" and subject to smaller changes. Last updated **2019-06-11**. - -# A quick note on compilation - -Major differences in performance can be seen based solely on compiler and/or linker options. Important is to compile with some kind of link-time-optimization mode, preferably with static linking of this library such as including all C source files in the user program build step itself. Proper compilation and linking can lead to over 25% performance increase (in my case, YMMV). - -# Cross-platform benchmarks - -While the library is compatible with many platforms, Linux in particular is the preferred production system. Benchmarking has been done on Windows, Linux and macOS where Linux clearly stood out as significant winner. Windows performed about half that of Linux and macOS was not much better than Windows. Do run your production systems on Linux. - -# us_loop_t - The root per-thread resource and callback emitter - -```c -/* Returns a new event loop with user data extension */ -WIN32_EXPORT struct us_loop_t *us_create_loop(void *hint, void (*wakeup_cb)(struct us_loop_t *loop), void (*pre_cb)(struct us_loop_t *loop), void (*post_cb)(struct us_loop_t *loop), unsigned int ext_size); - -/* Frees the loop immediately */ -WIN32_EXPORT void us_loop_free(struct us_loop_t *loop); - -/* Returns the loop user data extension */ -WIN32_EXPORT void *us_loop_ext(struct us_loop_t *loop); - -/* Blocks the calling thread and drives the event loop until no more non-fallthrough polls are scheduled */ -WIN32_EXPORT void us_loop_run(struct us_loop_t *loop); - -/* Signals the loop from any thread to wake up and execute its wakeup handler from the loop's own running thread. - * This is the only fully thread-safe function and serves as the basis for thread safety */ -WIN32_EXPORT void us_wakeup_loop(struct us_loop_t *loop); - -/* Hook up timers in existing loop */ -WIN32_EXPORT void us_loop_integrate(struct us_loop_t *loop); - -/* Returns the loop iteration number */ -WIN32_EXPORT long long us_loop_iteration_number(struct us_loop_t *loop); -``` - -# us_socket_context_t - The per-behavior group of networking sockets - -```c -struct us_socket_context_options_t { - const char *key_file_name; - const char *cert_file_name; - const char *passphrase; - const char *dh_params_file_name; - const char *ca_file_name; - const char *ssl_ciphers; - int ssl_prefer_low_memory_usage; -}; - -/* A socket context holds shared callbacks and user data extension for associated sockets */ -WIN32_EXPORT struct us_socket_context_t *us_create_socket_context(int ssl, struct us_loop_t *loop, int ext_size, struct us_socket_context_options_t options); - -/* Delete resources allocated at creation time. */ -WIN32_EXPORT void us_socket_context_free(int ssl, struct us_socket_context_t *context); - -/* Setters of various async callbacks */ -WIN32_EXPORT void us_socket_context_on_open(int ssl, struct us_socket_context_t *context, struct us_socket_t *(*on_open)(struct us_socket_t *s, int is_client, char *ip, int ip_length)); -WIN32_EXPORT void us_socket_context_on_close(int ssl, struct us_socket_context_t *context, struct us_socket_t *(*on_close)(struct us_socket_t *s)); -WIN32_EXPORT void us_socket_context_on_data(int ssl, struct us_socket_context_t *context, struct us_socket_t *(*on_data)(struct us_socket_t *s, char *data, int length)); -WIN32_EXPORT void us_socket_context_on_writable(int ssl, struct us_socket_context_t *context, struct us_socket_t *(*on_writable)(struct us_socket_t *s)); -WIN32_EXPORT void us_socket_context_on_timeout(int ssl, struct us_socket_context_t *context, struct us_socket_t *(*on_timeout)(struct us_socket_t *s)); - -/* Emitted when a socket has been half-closed */ -WIN32_EXPORT void us_socket_context_on_end(int ssl, struct us_socket_context_t *context, struct us_socket_t *(*on_end)(struct us_socket_t *s)); - -/* Returns user data extension for this socket context */ -WIN32_EXPORT void *us_socket_context_ext(int ssl, struct us_socket_context_t *context); - -/* Listen for connections. Acts as the main driving cog in a server. Will call set async callbacks. */ -WIN32_EXPORT struct us_listen_socket_t *us_socket_context_listen(int ssl, struct us_socket_context_t *context, const char *host, int port, int options, int socket_ext_size); - -/* listen_socket.c/.h */ -WIN32_EXPORT void us_listen_socket_close(int ssl, struct us_listen_socket_t *ls); - -/* Land in on_open or on_close or return null or return socket */ -WIN32_EXPORT struct us_socket_t *us_socket_context_connect(int ssl, struct us_socket_context_t *context, const char *host, int port, int options, int socket_ext_size); - -/* Returns the loop for this socket context. */ -WIN32_EXPORT struct us_loop_t *us_socket_context_loop(int ssl, struct us_socket_context_t *context); - -/* Invalidates passed socket, returning a new resized socket which belongs to a different socket context. - * Used mainly for "socket upgrades" such as when transitioning from HTTP to WebSocket. */ -WIN32_EXPORT struct us_socket_t *us_socket_context_adopt_socket(int ssl, struct us_socket_context_t *context, struct us_socket_t *s, int ext_size); - -/* Create a child socket context which acts much like its own socket context with its own callbacks yet still relies on the - * parent socket context for some shared resources. Child socket contexts should be used together with socket adoptions and nothing else. */ -WIN32_EXPORT struct us_socket_context_t *us_create_child_socket_context(int ssl, struct us_socket_context_t *context, int context_ext_size); -``` - -# us_socket_t - The network connection (SSL or non-SSL) - -```c -/* Write up to length bytes of data. Returns actual bytes written. Will call the on_writable callback of active socket context on failure to write everything off in one go. -WIN32_EXPORT int us_socket_write(int ssl, struct us_socket_t *s, const char *data, int length); - -/* Set a low precision, high performance timer on a socket. A socket can only have one single active timer at any given point in time. Will remove any such pre set timer */ -WIN32_EXPORT void us_socket_timeout(int ssl, struct us_socket_t *s, unsigned int seconds); - -/* Return the user data extension of this socket */ -WIN32_EXPORT void *us_socket_ext(int ssl, struct us_socket_t *s); - -/* Return the socket context of this socket */ -WIN32_EXPORT struct us_socket_context_t *us_socket_context(int ssl, struct us_socket_t *s); - -/* Withdraw any msg_more status and flush any pending data */ -WIN32_EXPORT void us_socket_flush(int ssl, struct us_socket_t *s); - -/* Shuts down the connection by sending FIN and/or close_notify */ -WIN32_EXPORT void us_socket_shutdown(int ssl, struct us_socket_t *s); - -/* Returns whether the socket has been shut down or not */ -WIN32_EXPORT int us_socket_is_shut_down(int ssl, struct us_socket_t *s); - -/* Returns whether this socket has been closed. Only valid if memory has not yet been released. */ -WIN32_EXPORT int us_socket_is_closed(int ssl, struct us_socket_t *s); - -/* Immediately closes the socket */ -WIN32_EXPORT struct us_socket_t *us_socket_close(int ssl, struct us_socket_t *s); - -/* Copy remote (IP) address of socket, or fail with zero length. */ -WIN32_EXPORT void us_socket_remote_address(int ssl, struct us_socket_t *s, char *buf, int *length); -``` - -# Low level components - -## us_timer_t - High cost (very expensive resource) timers - -**NOTE:** Many slow servers use one timer per socket. That is incredibly inefficient and so uSockets will only use one single us_timer_t per every one us_loop_t. A similar design is utilized in the Linux kernel and is how you should think of timers yourself. - -```c -/* Create a new high precision, low performance timer. May fail and return null */ -WIN32_EXPORT struct us_timer_t *us_create_timer(struct us_loop_t *loop, int fallthrough, unsigned int ext_size); - -/* Returns user data extension for this timer */ -WIN32_EXPORT void *us_timer_ext(struct us_timer_t *timer); - -/* */ -WIN32_EXPORT void us_timer_close(struct us_timer_t *timer); - -/* Arm a timer with a delay from now and eventually a repeat delay. - * Specify 0 as repeat delay to disable repeating. Specify both 0 to disarm. */ -WIN32_EXPORT void us_timer_set(struct us_timer_t *timer, void (*cb)(struct us_timer_t *t), int ms, int repeat_ms); - -/* Returns the loop for this timer */ -WIN32_EXPORT struct us_loop_t *us_timer_loop(struct us_timer_t *t); -``` - -## us_poll_t - The eventing foundation of a socket or anything that has a file descriptor - -```c -/* A fallthrough poll does not keep the loop running, it falls through */ -WIN32_EXPORT struct us_poll_t *us_create_poll(struct us_loop_t *loop, int fallthrough, unsigned int ext_size); - -/* After stopping a poll you must manually free the memory */ -WIN32_EXPORT void us_poll_free(struct us_poll_t *p, struct us_loop_t *loop); - -/* Associate this poll with a socket descriptor and poll type */ -WIN32_EXPORT void us_poll_init(struct us_poll_t *p, LIBUS_SOCKET_DESCRIPTOR fd, int poll_type); - -/* Start, change and stop polling for events */ -WIN32_EXPORT void us_poll_start(struct us_poll_t *p, struct us_loop_t *loop, int events); -WIN32_EXPORT void us_poll_change(struct us_poll_t *p, struct us_loop_t *loop, int events); -WIN32_EXPORT void us_poll_stop(struct us_poll_t *p, struct us_loop_t *loop); - -/* Return what events we are polling for */ -WIN32_EXPORT int us_poll_events(struct us_poll_t *p); - -/* Returns the user data extension of this poll */ -WIN32_EXPORT void *us_poll_ext(struct us_poll_t *p); - -/* Get associated socket descriptor from a poll */ -WIN32_EXPORT LIBUS_SOCKET_DESCRIPTOR us_poll_fd(struct us_poll_t *p); - -/* Resize an active poll */ -WIN32_EXPORT struct us_poll_t *us_poll_resize(struct us_poll_t *p, struct us_loop_t *loop, unsigned int ext_size); -``` diff --git a/packages/bun-usockets/module.modulemap b/packages/bun-usockets/module.modulemap deleted file mode 100644 index d99c0c6b6265..000000000000 --- a/packages/bun-usockets/module.modulemap +++ /dev/null @@ -1,4 +0,0 @@ -module bun-usockets { - header "src/libusockets.h" - export * -} diff --git a/patches/ncrypto.patch b/patches/ncrypto.patch deleted file mode 100644 index 59b81b4e9e96..000000000000 --- a/patches/ncrypto.patch +++ /dev/null @@ -1,919 +0,0 @@ -diff --git a/include/ncrypto.h b/include/ncrypto.h -index be9e0ca..f8000de 100644 ---- a/include/ncrypto.h -+++ b/include/ncrypto.h -@@ -1,5 +1,15 @@ - #pragma once - -+#include "root.h" -+ -+#ifdef ASSERT_ENABLED -+#define NCRYPTO_DEVELOPMENT_CHECKS 1 -+#endif -+ -+#include -+#include -+#include -+ - #include - #include - #include -@@ -61,30 +71,11 @@ namespace ncrypto { - - #if NCRYPTO_DEVELOPMENT_CHECKS - #define NCRYPTO_STR(x) #x --#define NCRYPTO_REQUIRE(EXPR) \ -- { \ -- if (!(EXPR) { abort(); }) } -- --#define NCRYPTO_FAIL(MESSAGE) \ -- do { \ -- std::cerr << "FAIL: " << (MESSAGE) << std::endl; \ -- abort(); \ -- } while (0); --#define NCRYPTO_ASSERT_EQUAL(LHS, RHS, MESSAGE) \ -- do { \ -- if (LHS != RHS) { \ -- std::cerr << "Mismatch: '" << LHS << "' - '" << RHS << "'" << std::endl; \ -- NCRYPTO_FAIL(MESSAGE); \ -- } \ -- } while (0); --#define NCRYPTO_ASSERT_TRUE(COND) \ -- do { \ -- if (!(COND)) { \ -- std::cerr << "Assert at line " << __LINE__ << " of file " << __FILE__ \ -- << std::endl; \ -- NCRYPTO_FAIL(NCRYPTO_STR(COND)); \ -- } \ -- } while (0); -+#define NCRYPTO_REQUIRE(EXPR) ASSERT_WITH_MESSAGE(EXPR, "Assertion failed") -+#define NCRYPTO_FAIL(MESSAGE) ASSERT_WITH_MESSAGE(false, MESSAGE) -+#define NCRYPTO_ASSERT_EQUAL(LHS, RHS, MESSAGE) \ -+ ASSERT_WITH_MESSAGE(LHS == RHS, MESSAGE) -+#define NCRYPTO_ASSERT_TRUE(COND) ASSERT_WITH_MESSAGE(COND, NCRYPTO_STR(COND)) - #else - #define NCRYPTO_FAIL(MESSAGE) - #define NCRYPTO_ASSERT_EQUAL(LHS, RHS, MESSAGE) -@@ -131,9 +122,9 @@ class CryptoErrorList final { - void capture(); - - // Add an error message to the end of the stack. -- void add(std::string message); -+ void add(WTF::String message); - -- inline const std::string& peek_back() const { return errors_.back(); } -+ inline const WTF::String& peek_back() const { return errors_.back(); } - inline size_t size() const { return errors_.size(); } - inline bool empty() const { return errors_.empty(); } - -@@ -142,11 +133,11 @@ class CryptoErrorList final { - inline auto rbegin() const noexcept { return errors_.rbegin(); } - inline auto rend() const noexcept { return errors_.rend(); } - -- std::optional pop_back(); -- std::optional pop_front(); -+ std::optional pop_back(); -+ std::optional pop_front(); - - private: -- std::list errors_; -+ std::list errors_; - }; - - // Forcibly clears the error stack on destruction. This stops stale errors -@@ -277,12 +268,12 @@ class Cipher final { - int getIvLength() const; - int getKeyLength() const; - int getBlockSize() const; -- std::string_view getModeLabel() const; -- std::string_view getName() const; -+ WTF::ASCIILiteral getModeLabel() const; -+ WTF::String getName() const; - - bool isSupportedAuthenticatedMode() const; - -- static const Cipher FromName(std::string_view name); -+ static const Cipher FromName(WTF::StringView name); - static const Cipher FromNid(int nid); - static const Cipher FromCtx(const CipherCtxPointer& ctx); - -@@ -336,6 +327,8 @@ class Dsa final { - }; - - class BignumPointer final { -+ WTF_MAKE_TZONE_ALLOCATED(BignumPointer); -+ - public: - BignumPointer() = default; - explicit BignumPointer(BIGNUM* bignum); -@@ -429,8 +422,8 @@ class Rsa final { - const BIGNUM* qi; - }; - struct PssParams { -- std::string_view digest = "sha1"; -- std::optional mgf1_digest = "sha1"; -+ WTF::StringView digest = "sha1"_s; -+ std::optional mgf1_digest = "sha1"_s; - int64_t salt_length = 20; - }; - -@@ -465,7 +458,7 @@ class Ec final { - const EC_GROUP* getGroup() const; - int getCurve() const; - uint32_t getDegree() const; -- std::string getCurveName() const; -+ WTF::String getCurveName() const; - const EC_POINT* getPublicKey() const; - const BIGNUM* getPrivateKey() const; - -@@ -535,13 +528,15 @@ class DataPointer final { - }; - - class BIOPointer final { -+ WTF_MAKE_TZONE_ALLOCATED(BIOPointer); -+ - public: - static BIOPointer NewMem(); - static BIOPointer NewSecMem(); - static BIOPointer New(const BIO_METHOD* method); - static BIOPointer New(const void* data, size_t len); - static BIOPointer New(const BIGNUM* bn); -- static BIOPointer NewFile(std::string_view filename, std::string_view mode); -+ static BIOPointer NewFile(WTF::StringView filename, WTF::StringView mode); - static BIOPointer NewFp(FILE* fd, int flags); - - template -@@ -575,7 +570,7 @@ class BIOPointer final { - - bool resetBio() const; - -- static int Write(BIOPointer* bio, std::string_view message); -+ static int Write(BIOPointer* bio, WTF::StringView message); - - template - static void Printf(BIOPointer* bio, const char* format, Args... args) { -@@ -588,6 +583,8 @@ class BIOPointer final { - }; - - class CipherCtxPointer final { -+ WTF_MAKE_TZONE_ALLOCATED(CipherCtxPointer); -+ - public: - static CipherCtxPointer New(); - -@@ -630,6 +627,8 @@ class CipherCtxPointer final { - }; - - class EVPKeyCtxPointer final { -+ WTF_MAKE_TZONE_ALLOCATED(EVPKeyCtxPointer); -+ - public: - EVPKeyCtxPointer(); - explicit EVPKeyCtxPointer(EVP_PKEY_CTX* ctx); -@@ -697,6 +696,8 @@ class EVPKeyCtxPointer final { - }; - - class EVPKeyPointer final { -+ WTF_MAKE_TZONE_ALLOCATED(EVPKeyPointer); -+ - public: - static EVPKeyPointer New(); - static EVPKeyPointer NewRawPublic(int id, -@@ -821,6 +822,8 @@ class EVPKeyPointer final { - }; - - class DHPointer final { -+ WTF_MAKE_TZONE_ALLOCATED(DHPointer); -+ - public: - enum class FindGroupOption { - NONE, -@@ -833,9 +836,9 @@ class DHPointer final { - static BignumPointer GetStandardGenerator(); - - static BignumPointer FindGroup( -- const std::string_view name, -+ const WTF::StringView name, - FindGroupOption option = FindGroupOption::NONE); -- static DHPointer FromGroup(const std::string_view name, -+ static DHPointer FromGroup(const WTF::StringView name, - FindGroupOption option = FindGroupOption::NONE); - - static DHPointer New(BignumPointer&& p, BignumPointer&& g); -@@ -910,6 +913,8 @@ struct StackOfX509Deleter { - using StackOfX509 = std::unique_ptr; - - class SSLCtxPointer final { -+ WTF_MAKE_TZONE_ALLOCATED(SSLCtxPointer); -+ - public: - SSLCtxPointer() = default; - explicit SSLCtxPointer(SSL_CTX* ctx); -@@ -943,6 +948,8 @@ class SSLCtxPointer final { - }; - - class SSLPointer final { -+ WTF_MAKE_TZONE_ALLOCATED(SSLPointer); -+ - public: - SSLPointer() = default; - explicit SSLPointer(SSL* ssl); -@@ -961,31 +968,33 @@ class SSLPointer final { - bool setSession(const SSLSessionPointer& session); - bool setSniContext(const SSLCtxPointer& ctx) const; - -- const std::string_view getClientHelloAlpn() const; -- const std::string_view getClientHelloServerName() const; -+ const WTF::StringView getClientHelloAlpn() const; -+ const WTF::StringView getClientHelloServerName() const; - -- std::optional getServerName() const; -+ std::optional getServerName() const; - X509View getCertificate() const; - EVPKeyPointer getPeerTempKey() const; - const SSL_CIPHER* getCipher() const; - bool isServer() const; - -- std::optional getCipherName() const; -- std::optional getCipherStandardName() const; -- std::optional getCipherVersion() const; -+ std::optional getCipherName() const; -+ std::optional getCipherStandardName() const; -+ std::optional getCipherVersion() const; - - std::optional verifyPeerCertificate() const; - -- void getCiphers(std::function cb) const; -+ void getCiphers(WTF::Function&& cb) const; - - static SSLPointer New(const SSLCtxPointer& ctx); -- static std::optional GetServerName(const SSL* ssl); -+ static std::optional GetServerName(const SSL* ssl); - - private: - DeleteFnPtr ssl_; - }; - - class X509Name final { -+ WTF_MAKE_TZONE_ALLOCATED(X509Name); -+ - public: - X509Name(); - explicit X509Name(const X509_NAME* name); -@@ -1007,7 +1016,7 @@ class X509Name final { - operator bool() const; - bool operator==(const Iterator& other) const; - bool operator!=(const Iterator& other) const; -- std::pair operator*() const; -+ std::pair operator*() const; - - private: - const X509Name& name_; -@@ -1062,7 +1071,7 @@ class X509View final { - bool checkPrivateKey(const EVPKeyPointer& pkey) const; - bool checkPublicKey(const EVPKeyPointer& pkey) const; - -- std::optional getFingerprint(const EVP_MD* method) const; -+ std::optional getFingerprint(const EVP_MD* method) const; - - X509Pointer clone() const; - -@@ -1072,16 +1081,16 @@ class X509View final { - INVALID_NAME, - OPERATION_FAILED, - }; -- CheckMatch checkHost(const std::string_view host, int flags, -+ CheckMatch checkHost(const std::span host, int flags, - DataPointer* peerName = nullptr) const; -- CheckMatch checkEmail(const std::string_view email, int flags) const; -- CheckMatch checkIp(const std::string_view ip, int flags) const; -+ CheckMatch checkEmail(const std::span email, int flags) const; -+ CheckMatch checkIp(const char* ip, int flags) const; - -- using UsageCallback = std::function; -+ using UsageCallback = WTF::Function)>; - bool enumUsages(UsageCallback callback) const; - - template -- using KeyCallback = std::function; -+ using KeyCallback = WTF::Function; - bool ifRsa(KeyCallback callback) const; - bool ifEc(KeyCallback callback) const; - -@@ -1090,6 +1099,8 @@ class X509View final { - }; - - class X509Pointer final { -+ WTF_MAKE_TZONE_ALLOCATED(X509Pointer); -+ - public: - static Result Parse(Buffer buffer); - static X509Pointer IssuerFrom(const SSLPointer& ssl, const X509View& view); -@@ -1114,14 +1125,16 @@ class X509Pointer final { - X509View view() const; - operator X509View() const { return view(); } - -- static std::string_view ErrorCode(int32_t err); -- static std::optional ErrorReason(int32_t err); -+ static WTF::ASCIILiteral ErrorCode(int32_t err); -+ static std::optional ErrorReason(int32_t err); - - private: - DeleteFnPtr cert_; - }; - - class ECDSASigPointer final { -+ WTF_MAKE_TZONE_ALLOCATED(ECDSASigPointer); -+ - public: - explicit ECDSASigPointer(); - explicit ECDSASigPointer(ECDSA_SIG* sig); -@@ -1154,6 +1167,8 @@ class ECDSASigPointer final { - }; - - class ECGroupPointer final { -+ WTF_MAKE_TZONE_ALLOCATED(ECGroupPointer); -+ - public: - explicit ECGroupPointer(); - explicit ECGroupPointer(EC_GROUP* group); -@@ -1176,6 +1191,8 @@ class ECGroupPointer final { - }; - - class ECPointPointer final { -+ WTF_MAKE_TZONE_ALLOCATED(ECPointPointer); -+ - public: - ECPointPointer(); - explicit ECPointPointer(EC_POINT* point); -@@ -1202,6 +1219,8 @@ class ECPointPointer final { - }; - - class ECKeyPointer final { -+ WTF_MAKE_TZONE_ALLOCATED(ECKeyPointer); -+ - public: - ECKeyPointer(); - explicit ECKeyPointer(EC_KEY* key); -@@ -1242,6 +1261,8 @@ class ECKeyPointer final { - }; - - class EVPMDCtxPointer final { -+ WTF_MAKE_TZONE_ALLOCATED(EVPMDCtxPointer); -+ - public: - EVPMDCtxPointer(); - explicit EVPMDCtxPointer(EVP_MD_CTX* ctx); -@@ -1286,6 +1307,8 @@ class EVPMDCtxPointer final { - }; - - class HMACCtxPointer final { -+ WTF_MAKE_TZONE_ALLOCATED(HMACCtxPointer); -+ - public: - HMACCtxPointer(); - explicit HMACCtxPointer(HMAC_CTX* ctx); -@@ -1331,7 +1354,7 @@ class EnginePointer final { - - bool setAsDefault(uint32_t flags, CryptoErrorList* errors = nullptr); - bool init(bool finish_on_exit = false); -- EVPKeyPointer loadPrivateKey(const std::string_view key_name); -+ EVPKeyPointer loadPrivateKey(const WTF::StringView key_name); - - // Release ownership of the ENGINE* pointer. - ENGINE* release(); -@@ -1339,7 +1362,7 @@ class EnginePointer final { - // Retrieve an OpenSSL Engine instance by name. If the name does not - // identify a valid named engine, the returned EnginePointer will be - // empty. -- static EnginePointer getEngineByName(const std::string_view name, -+ static EnginePointer getEngineByName(const WTF::StringView name, - CryptoErrorList* errors = nullptr); - - // Call once when initializing OpenSSL at startup for the process. -@@ -1396,8 +1419,8 @@ DataPointer ExportChallenge(const Buffer& buf); - // ============================================================================ - // KDF - --const EVP_MD* getDigestByName(const std::string_view name); --const EVP_CIPHER* getCipherByName(const std::string_view name); -+const EVP_MD* getDigestByName(const WTF::StringView name); -+const EVP_CIPHER* getCipherByName(const WTF::StringView name); - - // Verify that the specified HKDF output length is valid for the given digest. - // The maximum length for HKDF output for a given digest is 255 times the -diff --git a/src/ncrypto.cpp b/src/ncrypto.cpp -index 2e411ce..2315eb5 100644 ---- a/src/ncrypto.cpp -+++ b/src/ncrypto.cpp -@@ -1,3 +1,8 @@ -+#include "root.h" -+#include "wtf/text/ASCIILiteral.h" -+#include "wtf/text/StringImpl.h" -+#include "wtf/text/WTFString.h" -+ - #include "ncrypto.h" - - #include -@@ -75,22 +80,22 @@ void CryptoErrorList::capture() { - while (const auto err = ERR_get_error()) { - char buf[256]; - ERR_error_string_n(err, buf, sizeof(buf)); -- errors_.emplace_front(buf); -+ errors_.emplace_front(WTF::String::fromUTF8(buf)); - } - } - --void CryptoErrorList::add(std::string error) { errors_.push_back(error); } -+void CryptoErrorList::add(WTF::String error) { errors_.push_back(error); } - --std::optional CryptoErrorList::pop_back() { -+std::optional CryptoErrorList::pop_back() { - if (errors_.empty()) return std::nullopt; -- std::string error = errors_.back(); -+ WTF::String error = errors_.back(); - errors_.pop_back(); - return error; - } - --std::optional CryptoErrorList::pop_front() { -+std::optional CryptoErrorList::pop_front() { - if (errors_.empty()) return std::nullopt; -- std::string error = errors_.front(); -+ WTF::String error = errors_.front(); - errors_.pop_front(); - return error; - } -@@ -1104,7 +1109,8 @@ bool X509View::checkPublicKey(const EVPKeyPointer& pkey) const { - return X509_verify(const_cast(cert_), pkey.get()) == 1; - } - --X509View::CheckMatch X509View::checkHost(const std::string_view host, int flags, -+X509View::CheckMatch X509View::checkHost(const std::span host, -+ int flags, - DataPointer* peerName) const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) return CheckMatch::NO_MATCH; -@@ -1127,7 +1133,7 @@ X509View::CheckMatch X509View::checkHost(const std::string_view host, int flags, - } - } - --X509View::CheckMatch X509View::checkEmail(const std::string_view email, -+X509View::CheckMatch X509View::checkEmail(const std::span email, - int flags) const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) return CheckMatch::NO_MATCH; -@@ -1144,11 +1150,10 @@ X509View::CheckMatch X509View::checkEmail(const std::string_view email, - } - } - --X509View::CheckMatch X509View::checkIp(const std::string_view ip, -- int flags) const { -+X509View::CheckMatch X509View::checkIp(const char* ip, int flags) const { - ClearErrorOnReturn clearErrorOnReturn; - if (cert_ == nullptr) return CheckMatch::NO_MATCH; -- switch (X509_check_ip_asc(const_cast(cert_), ip.data(), flags)) { -+ switch (X509_check_ip_asc(const_cast(cert_), ip, flags)) { - case 0: - return CheckMatch::NO_MATCH; - case 1: -@@ -1172,7 +1177,7 @@ X509View X509View::From(const SSLCtxPointer& ctx) { - return X509View(SSL_CTX_get0_certificate(ctx.get())); - } - --std::optional X509View::getFingerprint( -+std::optional X509View::getFingerprint( - const EVP_MD* method) const { - unsigned int md_size; - unsigned char md[EVP_MAX_MD_SIZE]; -@@ -1180,7 +1185,9 @@ std::optional X509View::getFingerprint( - - if (X509_digest(get(), method, md, &md_size)) { - if (md_size == 0) return std::nullopt; -- std::string fingerprint((md_size * 3) - 1, 0); -+ std::span fingerprint; -+ WTF::String fingerprintStr = -+ WTF::String::createUninitialized((md_size * 3) - 1, fingerprint); - for (unsigned int i = 0; i < md_size; i++) { - auto idx = 3 * i; - fingerprint[idx] = hex[(md[i] & 0xf0) >> 4]; -@@ -1189,7 +1196,7 @@ std::optional X509View::getFingerprint( - fingerprint[idx + 2] = ':'; - } - -- return fingerprint; -+ return fingerprintStr; - } - - return std::nullopt; -@@ -1299,10 +1306,10 @@ X509Pointer X509Pointer::PeerFrom(const SSLPointer& ssl) { - // When adding or removing errors below, please also update the list in the API - // documentation. See the "OpenSSL Error Codes" section of doc/api/errors.md - // Also *please* update the respective section in doc/api/tls.md as well --std::string_view X509Pointer::ErrorCode(int32_t err) { // NOLINT(runtime/int) -+WTF::ASCIILiteral X509Pointer::ErrorCode(int32_t err) { // NOLINT(runtime/int) - #define CASE(CODE) \ - case X509_V_ERR_##CODE: \ -- return #CODE; -+ return #CODE##_s; - switch (err) { - CASE(UNABLE_TO_GET_ISSUER_CERT) - CASE(UNABLE_TO_GET_CRL) -@@ -1334,12 +1341,24 @@ std::string_view X509Pointer::ErrorCode(int32_t err) { // NOLINT(runtime/int) - CASE(HOSTNAME_MISMATCH) - } - #undef CASE -- return "UNSPECIFIED"; -+ return "UNSPECIFIED"_s; - } - --std::optional X509Pointer::ErrorReason(int32_t err) { -+std::optional X509Pointer::ErrorReason(int32_t err) { - if (err == X509_V_OK) return std::nullopt; -- return X509_verify_cert_error_string(err); -+ -+ // TODO(dylan-conway): delete this switch? -+ switch (err) { -+#define V(name, msg) \ -+ case X509_V_ERR_##name: \ -+ return msg##_s; -+ V(HOSTNAME_MISMATCH, "Hostname does not match certificate") -+ V(EMAIL_MISMATCH, "Email address does not match certificate") -+ V(IP_ADDRESS_MISMATCH, "IP address does not match certificate") -+#undef V -+ } -+ return WTF::ASCIILiteral::fromLiteralUnsafe( -+ X509_verify_cert_error_string(err)); - } - - // ============================================================================ -@@ -1385,9 +1404,10 @@ BIOPointer BIOPointer::New(const void* data, size_t len) { - return BIOPointer(BIO_new_mem_buf(data, len)); - } - --BIOPointer BIOPointer::NewFile(std::string_view filename, -- std::string_view mode) { -- return BIOPointer(BIO_new_file(filename.data(), mode.data())); -+BIOPointer BIOPointer::NewFile(WTF::StringView filename, WTF::StringView mode) { -+ auto filenameUtf8 = filename.utf8(); -+ auto modeUtf8 = mode.utf8(); -+ return BIOPointer(BIO_new_file(filenameUtf8.data(), modeUtf8.data())); - } - - BIOPointer BIOPointer::NewFp(FILE* fd, int close_flag) { -@@ -1400,20 +1420,18 @@ BIOPointer BIOPointer::New(const BIGNUM* bn) { - return res; - } - --int BIOPointer::Write(BIOPointer* bio, std::string_view message) { -- if (bio == nullptr || !*bio) return 0; -- return BIO_write(bio->get(), message.data(), message.size()); -+int BIOPointer::Write(BIOPointer* bio, WTF::StringView message) { -+ auto messageUtf8 = message.utf8(); -+ return Write(bio, messageUtf8.span()); - } - - // ============================================================================ - // DHPointer - - namespace { --bool EqualNoCase(const std::string_view a, const std::string_view b) { -- if (a.size() != b.size()) return false; -- return std::equal(a.begin(), a.end(), b.begin(), b.end(), [](char a, char b) { -- return std::tolower(a) == std::tolower(b); -- }); -+bool EqualNoCase(const WTF::StringView a, const WTF::StringView b) { -+ if (a.length() != b.length()) return false; -+ return a.startsWithIgnoringASCIICase(b); - } - } // namespace - -@@ -1433,23 +1451,23 @@ void DHPointer::reset(DH* dh) { dh_.reset(dh); } - - DH* DHPointer::release() { return dh_.release(); } - --BignumPointer DHPointer::FindGroup(const std::string_view name, -+BignumPointer DHPointer::FindGroup(const WTF::StringView name, - FindGroupOption option) { - #define V(n, p) \ - if (EqualNoCase(name, n)) return BignumPointer(p(nullptr)); - if (option != FindGroupOption::NO_SMALL_PRIMES) { - #ifndef OPENSSL_IS_BORINGSSL - // Boringssl does not support the 768 and 1024 small primes -- V("modp1", BN_get_rfc2409_prime_768); -- V("modp2", BN_get_rfc2409_prime_1024); -+ V("modp1"_s, BN_get_rfc2409_prime_768); -+ V("modp2"_s, BN_get_rfc2409_prime_1024); - #endif -- V("modp5", BN_get_rfc3526_prime_1536); -+ V("modp5"_s, BN_get_rfc3526_prime_1536); - } -- V("modp14", BN_get_rfc3526_prime_2048); -- V("modp15", BN_get_rfc3526_prime_3072); -- V("modp16", BN_get_rfc3526_prime_4096); -- V("modp17", BN_get_rfc3526_prime_6144); -- V("modp18", BN_get_rfc3526_prime_8192); -+ V("modp14"_s, BN_get_rfc3526_prime_2048); -+ V("modp15"_s, BN_get_rfc3526_prime_3072); -+ V("modp16"_s, BN_get_rfc3526_prime_4096); -+ V("modp17"_s, BN_get_rfc3526_prime_6144); -+ V("modp18"_s, BN_get_rfc3526_prime_8192); - #undef V - return {}; - } -@@ -1461,7 +1479,7 @@ BignumPointer DHPointer::GetStandardGenerator() { - return bn; - } - --DHPointer DHPointer::FromGroup(const std::string_view name, -+DHPointer DHPointer::FromGroup(const WTF::StringView name, - FindGroupOption option) { - auto group = FindGroup(name, option); - if (!group) return {}; // Unable to find the named group. -@@ -1469,7 +1487,7 @@ DHPointer DHPointer::FromGroup(const std::string_view name, - auto generator = GetStandardGenerator(); - if (!generator) return {}; // Unable to create the generator. - -- return New(std::move(group), std::move(generator)); -+ return New(WTFMove(group), WTFMove(generator)); - } - - DHPointer DHPointer::New(BignumPointer&& p, BignumPointer&& g) { -@@ -1663,17 +1681,24 @@ DataPointer DHPointer::stateless(const EVPKeyPointer& ourKey, - // ============================================================================ - // KDF - --const EVP_MD* getDigestByName(const std::string_view name) { -+const EVP_MD* getDigestByName(const WTF::StringView name) { - // Historically, "dss1" and "DSS1" were DSA aliases for SHA-1 - // exposed through the public API. -- if (name == "dss1" || name == "DSS1") [[unlikely]] { -+ if (name == "dss1"_s || name == "DSS1"_s) [[unlikely]] { - return EVP_sha1(); - } -- return EVP_get_digestbyname(name.data()); -+ -+ // if (name == "ripemd160WithRSA"_s || name == "RSA-RIPEMD160"_s) { -+ // return EVP_ripemd160(); -+ // } -+ -+ auto nameUtf8 = name.utf8(); -+ return EVP_get_digestbyname(nameUtf8.data()); - } - --const EVP_CIPHER* getCipherByName(const std::string_view name) { -- return EVP_get_cipherbyname(name.data()); -+const EVP_CIPHER* getCipherByName(const WTF::StringView name) { -+ auto nameUtf8 = name.utf8(); -+ return EVP_get_cipherbyname(nameUtf8.data()); - } - - bool checkHkdfLength(const EVP_MD* md, size_t length) { -@@ -2499,7 +2524,7 @@ SSLPointer SSLPointer::New(const SSLCtxPointer& ctx) { - } - - void SSLPointer::getCiphers( -- std::function cb) const { -+ WTF::Function&& cb) const { - if (!ssl_) return; - STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(get()); - -@@ -2507,16 +2532,16 @@ void SSLPointer::getCiphers( - // document them, but since there are only 5, easier to just add them manually - // and not have to explain their absence in the API docs. They are lower-cased - // because the docs say they will be. -- static constexpr const char* TLS13_CIPHERS[] = { -- "tls_aes_256_gcm_sha384", "tls_chacha20_poly1305_sha256", -- "tls_aes_128_gcm_sha256", "tls_aes_128_ccm_8_sha256", -- "tls_aes_128_ccm_sha256"}; -+ static constexpr WTF::ASCIILiteral TLS13_CIPHERS[] = { -+ "tls_aes_256_gcm_sha384"_s, "tls_chacha20_poly1305_sha256"_s, -+ "tls_aes_128_gcm_sha256"_s, "tls_aes_128_ccm_8_sha256"_s, -+ "tls_aes_128_ccm_sha256"_s}; - - const int n = sk_SSL_CIPHER_num(ciphers); - - for (int i = 0; i < n; ++i) { - const SSL_CIPHER* cipher = sk_SSL_CIPHER_value(ciphers, i); -- cb(SSL_CIPHER_get_name(cipher)); -+ cb(WTF::ASCIILiteral::fromLiteralUnsafe(SSL_CIPHER_get_name(cipher))); - } - - for (unsigned i = 0; i < 5; ++i) { -@@ -2562,7 +2587,7 @@ std::optional SSLPointer::verifyPeerCertificate() const { - return std::nullopt; - } - --const std::string_view SSLPointer::getClientHelloAlpn() const { -+const WTF::StringView SSLPointer::getClientHelloAlpn() const { - if (ssl_ == nullptr) return {}; - #ifndef OPENSSL_IS_BORINGSSL - const unsigned char* buf; -@@ -2585,7 +2610,7 @@ const std::string_view SSLPointer::getClientHelloAlpn() const { - #endif - } - --const std::string_view SSLPointer::getClientHelloServerName() const { -+const WTF::StringView SSLPointer::getClientHelloServerName() const { - if (ssl_ == nullptr) return {}; - #ifndef OPENSSL_IS_BORINGSSL - const unsigned char* buf; -@@ -2613,15 +2638,14 @@ const std::string_view SSLPointer::getClientHelloServerName() const { - #endif - } - --std::optional SSLPointer::GetServerName( -- const SSL* ssl) { -+std::optional SSLPointer::GetServerName(const SSL* ssl) { - if (ssl == nullptr) return std::nullopt; - auto res = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); - if (res == nullptr) return std::nullopt; -- return res; -+ return WTF::String::fromUTF8(res); - } - --std::optional SSLPointer::getServerName() const { -+std::optional SSLPointer::getServerName() const { - if (!ssl_) return std::nullopt; - return GetServerName(get()); - } -@@ -2650,22 +2674,28 @@ EVPKeyPointer SSLPointer::getPeerTempKey() const { - return EVPKeyPointer(raw_key); - } - --std::optional SSLPointer::getCipherName() const { -+std::optional SSLPointer::getCipherName() const { - auto cipher = getCipher(); - if (cipher == nullptr) return std::nullopt; -- return SSL_CIPHER_get_name(cipher); -+ const char* name = SSL_CIPHER_get_name(cipher); -+ if (!name) return std::nullopt; -+ return WTF::StringView::fromLatin1(name); - } - --std::optional SSLPointer::getCipherStandardName() const { -+std::optional SSLPointer::getCipherStandardName() const { - auto cipher = getCipher(); - if (cipher == nullptr) return std::nullopt; -- return SSL_CIPHER_standard_name(cipher); -+ const char* name = SSL_CIPHER_standard_name(cipher); -+ if (!name) return std::nullopt; -+ return WTF::StringView::fromLatin1(name); - } - --std::optional SSLPointer::getCipherVersion() const { -+std::optional SSLPointer::getCipherVersion() const { - auto cipher = getCipher(); - if (cipher == nullptr) return std::nullopt; -- return SSL_CIPHER_get_version(cipher); -+ auto version = SSL_CIPHER_get_version(cipher); -+ if (!version) return std::nullopt; -+ return WTF::StringView::fromLatin1(version); - } - - SSLCtxPointer::SSLCtxPointer(SSL_CTX* ctx) : ctx_(ctx) {} -@@ -2713,8 +2743,9 @@ bool SSLCtxPointer::setGroups(const char* groups) { - - // ============================================================================ - --const Cipher Cipher::FromName(std::string_view name) { -- return Cipher(EVP_get_cipherbyname(name.data())); -+const Cipher Cipher::FromName(WTF::StringView name) { -+ auto nameUtf8 = name.utf8(); -+ return Cipher(EVP_get_cipherbyname(nameUtf8.data())); - } - - const Cipher Cipher::FromNid(int nid) { -@@ -2750,40 +2781,40 @@ int Cipher::getNid() const { - return EVP_CIPHER_nid(cipher_); - } - --std::string_view Cipher::getModeLabel() const { -+WTF::ASCIILiteral Cipher::getModeLabel() const { - if (!cipher_) return {}; - switch (getMode()) { - case EVP_CIPH_CCM_MODE: -- return "ccm"; -+ return "ccm"_s; - case EVP_CIPH_CFB_MODE: -- return "cfb"; -+ return "cfb"_s; - case EVP_CIPH_CBC_MODE: -- return "cbc"; -+ return "cbc"_s; - case EVP_CIPH_CTR_MODE: -- return "ctr"; -+ return "ctr"_s; - case EVP_CIPH_ECB_MODE: -- return "ecb"; -+ return "ecb"_s; - case EVP_CIPH_GCM_MODE: -- return "gcm"; -+ return "gcm"_s; - case EVP_CIPH_OCB_MODE: -- return "ocb"; -+ return "ocb"_s; - case EVP_CIPH_OFB_MODE: -- return "ofb"; -+ return "ofb"_s; - case EVP_CIPH_WRAP_MODE: -- return "wrap"; -+ return "wrap"_s; - case EVP_CIPH_XTS_MODE: -- return "xts"; -+ return "xts"_s; - case EVP_CIPH_STREAM_CIPHER: -- return "stream"; -+ return "stream"_s; - } -- return "{unknown}"; -+ return "{unknown}"_s; - } - --std::string_view Cipher::getName() const { -+WTF::String Cipher::getName() const { - if (!cipher_) return {}; - // OBJ_nid2sn(EVP_CIPHER_nid(cipher)) is used here instead of - // EVP_CIPHER_name(cipher) for compatibility with BoringSSL. -- return OBJ_nid2sn(getNid()); -+ return WTF::String::fromUTF8(OBJ_nid2sn(getNid())); - } - - bool Cipher::isSupportedAuthenticatedMode() const { -@@ -3497,15 +3528,15 @@ const std::optional Rsa::getPssParams() const { - const RSA_PSS_PARAMS* params = RSA_get0_pss_params(rsa_); - if (params == nullptr) return std::nullopt; - Rsa::PssParams ret{ -- .digest = OBJ_nid2ln(NID_sha1), -- .mgf1_digest = OBJ_nid2ln(NID_sha1), -+ .digest = WTF::StringView::fromLatin1(OBJ_nid2ln(NID_sha1)), -+ .mgf1_digest = WTF::StringView::fromLatin1(OBJ_nid2ln(NID_sha1)), - .salt_length = 20, - }; - - if (params->hashAlgorithm != nullptr) { - const ASN1_OBJECT* hash_obj; - X509_ALGOR_get0(&hash_obj, nullptr, nullptr, params->hashAlgorithm); -- ret.digest = OBJ_nid2ln(OBJ_obj2nid(hash_obj)); -+ ret.digest = WTF::StringView::fromLatin1(OBJ_nid2ln(OBJ_obj2nid(hash_obj))); - } - - if (params->maskGenAlgorithm != nullptr) { -@@ -3515,7 +3546,8 @@ const std::optional Rsa::getPssParams() const { - if (mgf_nid == NID_mgf1) { - const ASN1_OBJECT* mgf1_hash_obj; - X509_ALGOR_get0(&mgf1_hash_obj, nullptr, nullptr, params->maskHash); -- ret.mgf1_digest = OBJ_nid2ln(OBJ_obj2nid(mgf1_hash_obj)); -+ ret.mgf1_digest = -+ WTF::StringView::fromLatin1(OBJ_nid2ln(OBJ_obj2nid(mgf1_hash_obj))); - } - } - -@@ -3627,8 +3659,8 @@ int Ec::getCurve() const { return EC_GROUP_get_curve_name(getGroup()); } - - uint32_t Ec::getDegree() const { return EC_GROUP_get_degree(getGroup()); } - --std::string Ec::getCurveName() const { -- return std::string(OBJ_nid2sn(getCurve())); -+WTF::String Ec::getCurveName() const { -+ return WTF::String::fromUTF8(OBJ_nid2sn(getCurve())); - } - - const EC_POINT* Ec::getPublicKey() const { return EC_KEY_get0_public_key(ec_); } -@@ -3891,7 +3923,7 @@ bool X509Name::Iterator::operator!=(const Iterator& other) const { - return loc_ != other.loc_; - } - --std::pair X509Name::Iterator::operator*() const { -+std::pair X509Name::Iterator::operator*() const { - if (loc_ == name_.total_) return {{}, {}}; - - X509_NAME_ENTRY* entry = X509_NAME_get_entry(name_, loc_); -@@ -3906,21 +3938,22 @@ std::pair X509Name::Iterator::operator*() const { - } - - int nid = OBJ_obj2nid(name); -- std::string name_str; -+ WTF::String name_str; - if (nid != NID_undef) { -- name_str = std::string(OBJ_nid2sn(nid)); -+ name_str = WTF::String::fromUTF8(OBJ_nid2sn(nid)); - } else { - char buf[80]; - OBJ_obj2txt(buf, sizeof(buf), name, 0); -- name_str = std::string(buf); -+ name_str = WTF::String::fromUTF8(buf); - } - - unsigned char* value_str; - int value_str_size = ASN1_STRING_to_UTF8(&value_str, value); - - return { -- std::move(name_str), -- std::string(reinterpret_cast(value_str), value_str_size)}; -+ name_str, -+ WTF::String::fromUTF8(std::span(value_str, value_str_size)), -+ }; - } - - // ============================================================================ diff --git a/src/js/builtins.d.ts b/src/js/builtins.d.ts index 2ef61951e30f..7d43df169845 100644 --- a/src/js/builtins.d.ts +++ b/src/js/builtins.d.ts @@ -328,7 +328,6 @@ declare function $autoAllocateChunkSize(): TODO; declare function $basename(): TODO; declare function $body(): TODO; declare function $bunNativePtr(): TODO; -declare function $bunNativeType(): TODO; declare function $byobRequest(): TODO; declare function $cancel(): TODO; declare function $close(): TODO; @@ -340,7 +339,6 @@ declare function $data(): TODO; declare function $dataView(): TODO; declare function $decode(): TODO; declare function $dirname(): TODO; -declare function $disturbed(): TODO; declare function $encoding(): TODO; declare function $end(): TODO; declare function $errno(): TODO; diff --git a/src/js/builtins/BunBuiltinNames.h b/src/js/builtins/BunBuiltinNames.h index fb23b64664d8..b3a6202f05f6 100644 --- a/src/js/builtins/BunBuiltinNames.h +++ b/src/js/builtins/BunBuiltinNames.h @@ -56,7 +56,6 @@ using namespace JSC; macro(blob) \ macro(body) \ macro(bunNativePtr) \ - macro(bunNativeType) \ macro(byobRequest) \ macro(bytes) \ macro(cancel) \ @@ -76,7 +75,6 @@ using namespace JSC; macro(decode) \ macro(dest) \ macro(dirname) \ - macro(disturbed) \ macro(domain) \ macro(drain) \ macro(encoding) \ diff --git a/src/js/node/_http_server.ts b/src/js/node/_http_server.ts index 89b6db00bacd..3d32533df07a 100644 --- a/src/js/node/_http_server.ts +++ b/src/js/node/_http_server.ts @@ -36,16 +36,12 @@ const { kRealListen, tlsSymbol, optionsSymbol, - kDeprecatedReplySymbol, headerStateSymbol, NodeHTTPHeaderState, kPendingCallbacks, kRequest, kCloseCallback, NodeHTTPResponseFlags, - emitErrorNextTickIfErrorListenerNT, - getIsNextIncomingMessageHTTPS, - setIsNextIncomingMessageHTTPS, callCloseCallback, emitCloseNT, NodeHTTPResponseAbortEvent, @@ -53,11 +49,7 @@ const { isTlsSymbol, hasServerResponseFinished, NodeHTTPBodyReadState, - controllerSymbol, - firstWriteSymbol, - deferredSymbol, eofInProgress, - runSymbol, drainMicrotasks, setServerCustomOptions, setServerAppFlags, @@ -115,7 +107,6 @@ const kServerResponse = Symbol("ServerResponse"); const kChunkedEncoding = Symbol("kChunkedEncoding"); const kShouldKeepAlive = Symbol("kShouldKeepAlive"); const kOptimizeEmptyRequests = Symbol("kOptimizeEmptyRequests"); -const GlobalPromise = globalThis.Promise; const kEmptyBuffer = Buffer.alloc(0); const ObjectKeys = Object.keys; const MathMin = Math.min; @@ -200,35 +191,6 @@ function strictContentLength(response) { } } -const ServerResponse_writeDeprecated = function _write(chunk, encoding, callback) { - if ($isCallable(encoding)) { - callback = encoding; - encoding = undefined; - } - if (!$isCallable(callback)) { - callback = undefined; - } - if (encoding && encoding !== "buffer") { - chunk = Buffer.from(chunk, encoding); - } - if (this.destroyed || this.finished) { - if (chunk) { - emitErrorNextTickIfErrorListenerNT(this, $ERR_STREAM_WRITE_AFTER_END(), callback); - } - return false; - } - if (this[firstWriteSymbol] === undefined && !this.headersSent) { - this[firstWriteSymbol] = chunk; - if (callback) callback(); - return; - } - - ensureReadableStreamController.$call(this, controller => { - controller.write(chunk); - if (callback) callback(); - }); -}; - const kParserOnTimeout = HTTPParser.kOnTimeout | 0; // Node attaches the llhttp HTTPParser to every server connection as @@ -275,11 +237,6 @@ function onNodeHTTPServerSocketTimeout() { if (!reqTimeout && !resTimeout && !serverTimeout) this.destroy(); } -function emitRequestCloseNT(self) { - callCloseCallback(self); - self.emit("close"); -} - function emitListeningNextTick(self, hostname, port) { if ((self.listening = !!self[serverSymbol])) { // TODO: remove the arguments @@ -644,26 +601,6 @@ Server.prototype.listen = function () { if (cluster === undefined) cluster = require("node:cluster"); - // const serverQuery = { - // // address: address, - // port: port, - // addressType: 4, - // // fd: fd, - // // flags, - // // backlog, - // // ...options, - // }; - // cluster._getServer(server, serverQuery, function listenOnPrimaryHandle(err, handle) { - // // err = checkBindError(err, port, handle); - // // if (err) { - // // throw new ExceptionWithHostPort(err, "bind", address, port); - // // } - // if (err) { - // throw err; - // } - // server[kRealListen](port, host, socketPath, onListen); - // }); - server.once("listening", () => { // No channel (NODE_UNIQUE_ID inherited by a plain child, or already disconnected): nothing to notify. if (!process.connected) return; @@ -695,7 +632,6 @@ Server.prototype[kRealListen] = function (tls, port, host, socketPath, reusePort const ResponseClass = this[optionsSymbol].ServerResponse || ServerResponse; const RequestClass = this[optionsSymbol].IncomingMessage || IncomingMessage; const canUseInternalAssignSocket = ResponseClass?.prototype.assignSocket === ServerResponse.prototype.assignSocket; - let isHTTPS = false; let server = this; if (tls) { @@ -748,8 +684,6 @@ Server.prototype[kRealListen] = function (tls, port, host, socketPath, reusePort connectHead?: Buffer, isPipelinedDispatch?: boolean, ) { - const prevIsNextIncomingMessageHTTPS = getIsNextIncomingMessageHTTPS(); - setIsNextIncomingMessageHTTPS(isHTTPS); if (!socket) { socket = new NodeHTTPServerSocket(server, socketHandle, !!tls); } @@ -894,7 +828,6 @@ Server.prototype[kRealListen] = function (tls, port, host, socketPath, reusePort http_res.once("finish", stopServerResponsePerf); } - setIsNextIncomingMessageHTTPS(prevIsNextIncomingMessageHTTPS); handle.onabort = socket[kBoundOnAbort] ??= onServerRequestEvent.bind(socket); // Like Node's connectionListener -> parserOnBody: body bytes flow into // the IncomingMessage as they arrive, and the push callback readStop()s @@ -1133,7 +1066,6 @@ Server.prototype[kRealListen] = function (tls, port, host, socketPath, reusePort }); getBunServerAllClosedPromise(this[serverSymbol]).$then(emitCloseNTServer.bind(this)); - isHTTPS = this[serverSymbol].protocol === "https"; applyServerCustomOptions(this); if (this?._unref) { @@ -2171,14 +2103,6 @@ function ServerResponse(req, options): void { this.useChunkedEncodingByDefault = true; - if ((this[kDeprecatedReplySymbol] = options?.[kDeprecatedReplySymbol])) { - this[controllerSymbol] = undefined; - this[firstWriteSymbol] = undefined; - this[deferredSymbol] = undefined; - this.write = ServerResponse_writeDeprecated; - this.end = ServerResponse_finalDeprecated; - } - this.req = req; this.sendDate = true; this._sent100 = false; @@ -3768,101 +3692,6 @@ function allowWritesToContinue() { this.emit("drain"); } -function drainHeadersIfObservable() { - if (this._implicitHeader === OriginalImplicitHeadFn && this.writeHead === OriginalWriteHeadFn) { - return; - } - - this._implicitHeader(); -} - -function ServerResponse_finalDeprecated(chunk, encoding, callback) { - if ($isCallable(encoding)) { - callback = encoding; - encoding = undefined; - } - if (!$isCallable(callback)) { - callback = undefined; - } - - if (this.destroyed || this.finished) { - if (chunk) { - emitErrorNextTickIfErrorListenerNT(this, $ERR_STREAM_WRITE_AFTER_END(), callback); - } - return false; - } - if (encoding && encoding !== "buffer") { - chunk = Buffer.from(chunk, encoding); - } - const req = this.req; - - const shouldEmitClose = req && req.emit && !this.finished; - if (!this.headersSent) { - let data = this[firstWriteSymbol]; - if (chunk) { - if (data) { - if (encoding) { - data = Buffer.from(data, encoding); - } - - data = new Blob([data, chunk]); - } else { - data = chunk; - } - } else if (!data) { - data = undefined; - } else { - data = new Blob([data]); - } - - this[firstWriteSymbol] = undefined; - this.finished = true; - this.headersSent = true; // https://github.com/oven-sh/bun/issues/3458 - drainHeadersIfObservable.$call(this); - this[kDeprecatedReplySymbol]( - new Response(data, { - headers: this.getHeaders(), - status: this.statusCode, - statusText: this.statusMessage ?? STATUS_CODES[this.statusCode], - }), - ); - if (shouldEmitClose) { - req.complete = true; - process.nextTick(emitRequestCloseNT, req); - } - callback?.(); - return; - } - - this.finished = true; - ensureReadableStreamController.$call(this, controller => { - if (chunk && encoding) { - chunk = Buffer.from(chunk, encoding); - } - - let prom; - if (chunk) { - controller.write(chunk); - prom = controller.end(); - } else { - prom = controller.end(); - } - - const handler = () => { - callback(); - const deferred = this[deferredSymbol]; - if (deferred) { - this[deferredSymbol] = undefined; - deferred(); - } - }; - if ($isPromise(prom)) prom.then(handler, handler); - else handler(); - }); -} - -// ServerResponse.prototype._final = ServerResponse_finalDeprecated; - OriginalWriteHeadFn = ServerResponse.prototype.writeHead; OriginalImplicitHeadFn = ServerResponse.prototype._implicitHeader; @@ -3982,44 +3811,6 @@ function storeHTTPOptions(options) { this[kOptimizeEmptyRequests] = optimizeEmptyRequests || false; } -function ensureReadableStreamController(run) { - const thisController = this[controllerSymbol]; - if (thisController) return run(thisController); - this.headersSent = true; - let firstWrite = this[firstWriteSymbol]; - const old_run = this[runSymbol]; - if (old_run) { - old_run.push(run); - return; - } - this[runSymbol] = [run]; - this[kDeprecatedReplySymbol]( - new Response( - new ReadableStream({ - type: "direct", - pull: controller => { - this[controllerSymbol] = controller; - if (firstWrite) controller.write(firstWrite); - firstWrite = undefined; - for (let run of this[runSymbol]) { - run(controller); - } - if (!this.finished) { - const { promise, resolve } = $newPromiseCapability(GlobalPromise); - this[deferredSymbol] = resolve; - return promise; - } - }, - }), - { - headers: this.getHeaders(), - status: this.statusCode, - statusText: this.statusMessage ?? STATUS_CODES[this.statusCode], - }, - ), - ); -} - export default { Server, ServerResponse, diff --git a/src/jsc/bindings/ImportMetaObject.h b/src/jsc/bindings/ImportMetaObject.h index 761959f17bb5..b3bc62f69d8f 100644 --- a/src/jsc/bindings/ImportMetaObject.h +++ b/src/jsc/bindings/ImportMetaObject.h @@ -10,7 +10,6 @@ extern "C" JSC_DECLARE_HOST_FUNCTION(functionImportMeta__resolveSync); extern "C" JSC_DECLARE_HOST_FUNCTION(functionImportMeta__resolveSyncPrivate); -extern "C" JSC::EncodedJSValue Bun__resolve(JSC::JSGlobalObject* global, JSC::EncodedJSValue specifier, JSC::EncodedJSValue from, bool is_esm); extern "C" JSC::EncodedJSValue Bun__resolveSync(JSC::JSGlobalObject* global, JSC::EncodedJSValue specifier, JSC::EncodedJSValue from, bool is_esm, bool isUserRequireResolve); extern "C" JSC::EncodedJSValue Bun__resolveSyncWithPaths(JSC::JSGlobalObject* global, JSC::EncodedJSValue specifier, JSC::EncodedJSValue from, bool is_esm, bool isUserRequireResolve, const BunString* paths, size_t paths_len); extern "C" JSC::EncodedJSValue Bun__resolveSyncWithSource(JSC::JSGlobalObject* global, JSC::EncodedJSValue specifier, BunString* from, bool is_esm, bool isUserRequireResolve); diff --git a/src/jsc/bindings/Weak.cpp b/src/jsc/bindings/Weak.cpp index cd7817c8eaaa..68ab951730fd 100644 --- a/src/jsc/bindings/Weak.cpp +++ b/src/jsc/bindings/Weak.cpp @@ -12,8 +12,6 @@ enum class WeakRefType : uint32_t { PostgreSQLQueryClient = 2, }; -typedef void (*WeakRefFinalizeFn)(void* context); - // clang-format off #define FOR_EACH_WEAK_REF_TYPE(macro) \ macro(FetchResponse) \ diff --git a/src/jsc/bindings/WriteBarrierList.h b/src/jsc/bindings/WriteBarrierList.h index 84345ca268f6..e9286b981329 100644 --- a/src/jsc/bindings/WriteBarrierList.h +++ b/src/jsc/bindings/WriteBarrierList.h @@ -36,11 +36,6 @@ class WriteBarrierList { m_list.append(JSC::WriteBarrier(vm, owner, value)); } - std::span> list() - { - return m_list.mutableSpan(); - } - // Move every element into `arguments` and clear the backing vector in one // linear pass under a single cellLock. void drainTo(JSC::JSCell* owner, JSC::MarkedArgumentBuffer& arguments) diff --git a/src/jsc/bindings/node/crypto/JSKeyObject.h b/src/jsc/bindings/node/crypto/JSKeyObject.h index b7bcc99a6caa..4fe3474f1f12 100644 --- a/src/jsc/bindings/node/crypto/JSKeyObject.h +++ b/src/jsc/bindings/node/crypto/JSKeyObject.h @@ -24,26 +24,6 @@ class JSKeyObject : public JSC::JSDestructibleObject { return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); } - static JSKeyObject* create(JSC::VM& vm, JSC::Structure* structure, JSC::JSGlobalObject* globalObject, KeyObject&& keyObject) - { - JSKeyObject* instance = new (NotNull, JSC::allocateCell(vm)) JSKeyObject(vm, structure, WTF::move(keyObject)); - instance->finishCreation(vm, globalObject); - return instance; - } - - template - static JSC::GCClient::IsoSubspace* subspaceFor(JSC::VM& vm) - { - if constexpr (mode == JSC::SubspaceAccess::Concurrently) - return nullptr; - return WebCore::subspaceForImpl( - vm, - [](auto& spaces) { return spaces.m_clientSubspaceForJSKeyObject.get(); }, - [](auto& spaces, auto&& space) { spaces.m_clientSubspaceForJSKeyObject = std::forward(space); }, - [](auto& spaces) { return spaces.m_subspaceForJSKeyObject.get(); }, - [](auto& spaces, auto&& space) { spaces.m_subspaceForJSKeyObject = std::forward(space); }); - } - JSKeyObject(JSC::VM& vm, JSC::Structure* structure, KeyObject&& keyObject) : Base(vm, structure) , m_handle(WTF::move(keyObject)) diff --git a/src/jsc/bindings/root.h b/src/jsc/bindings/root.h index 93e70d3859c0..c101d7e9d0ca 100644 --- a/src/jsc/bindings/root.h +++ b/src/jsc/bindings/root.h @@ -45,9 +45,6 @@ #define JSC_API_AVAILABLE(...) #define JSC_CLASS_AVAILABLE(...) JS_EXPORT #define JSC_API_DEPRECATED(...) -// Use zero since it will be less than any possible version number. -#define JSC_MAC_VERSION_TBA 0 -#define JSC_IOS_VERSION_TBA 0 #include diff --git a/src/jsc/bindings/v8-capture-stack-fixture.cjs b/src/jsc/bindings/v8-capture-stack-fixture.cjs deleted file mode 100644 index c8d21c775d26..000000000000 --- a/src/jsc/bindings/v8-capture-stack-fixture.cjs +++ /dev/null @@ -1,15 +0,0 @@ -let e = new Error(); - -const { noInline } = require("bun:jsc"); - -function sloppyWrapperFn() { - sloppyFn(); -} -noInline(sloppyWrapperFn); - -function sloppyFn() { - Error.captureStackTrace(e); - module.exports = e.stack; -} -noInline(sloppyFn); -sloppyWrapperFn(); diff --git a/src/jsc/bindings/webcore/DOMClientIsoSubspaces.h b/src/jsc/bindings/webcore/DOMClientIsoSubspaces.h index 08f84d970ec4..c714a49674ce 100644 --- a/src/jsc/bindings/webcore/DOMClientIsoSubspaces.h +++ b/src/jsc/bindings/webcore/DOMClientIsoSubspaces.h @@ -184,7 +184,6 @@ class DOMClientIsoSubspaces { std::unique_ptr m_clientSubspaceForJSHmac; std::unique_ptr m_clientSubspaceForJSHash; std::unique_ptr m_clientSubspaceForJSCipher; - std::unique_ptr m_clientSubspaceForJSKeyObject; std::unique_ptr m_clientSubspaceForJSSecretKeyObject; std::unique_ptr m_clientSubspaceForJSPublicKeyObject; std::unique_ptr m_clientSubspaceForJSPrivateKeyObject; diff --git a/src/jsc/bindings/webcore/DOMIsoSubspaces.h b/src/jsc/bindings/webcore/DOMIsoSubspaces.h index 703c758f3b2e..a3dc7eca7873 100644 --- a/src/jsc/bindings/webcore/DOMIsoSubspaces.h +++ b/src/jsc/bindings/webcore/DOMIsoSubspaces.h @@ -190,7 +190,6 @@ class DOMIsoSubspaces { std::unique_ptr m_subspaceForJSDiffieHellmanGroup; std::unique_ptr m_subspaceForJSECDH; std::unique_ptr m_subspaceForJSCipher; - std::unique_ptr m_subspaceForJSKeyObject; std::unique_ptr m_subspaceForJSSecretKeyObject; std::unique_ptr m_subspaceForJSPublicKeyObject; std::unique_ptr m_subspaceForJSPrivateKeyObject; diff --git a/src/jsc/bindings/webcore/EventNames.in b/src/jsc/bindings/webcore/EventNames.in deleted file mode 100644 index 8c0fb60721a3..000000000000 --- a/src/jsc/bindings/webcore/EventNames.in +++ /dev/null @@ -1,101 +0,0 @@ -namespace="Event" -factoryFunction=toNewlyCreated -useNamespaceAsSuffix=false - -Event -Events interfaceName=Event -HTMLEvents interfaceName=Event -AnimationEvent -AnimationPlaybackEvent -BeforeLoadEvent interfaceName=Event -BeforeUnloadEvent -ClipboardEvent -CloseEvent -CompositionEvent -CustomEvent -DragEvent -ExtendableEvent conditional=SERVICE_WORKER -ExtendableMessageEvent conditional=SERVICE_WORKER -ErrorEvent -FetchEvent conditional=SERVICE_WORKER -FocusEvent -FormDataEvent -HashChangeEvent -InputEvent -InputEvents interfaceName=InputEvent -KeyboardEvent -KeyboardEvents interfaceName=KeyboardEvent -MediaQueryListEvent -MessageEvent -MouseEvent -MouseEvents interfaceName=MouseEvent -MutationEvent -MutationEvents interfaceName=MutationEvent -OverflowEvent -PageTransitionEvent -PopStateEvent -ProgressEvent -PromiseRejectionEvent -PushEvent conditional=SERVICE_WORKER -PushSubscriptionChangeEvent conditional=SERVICE_WORKER -SubmitEvent -TextEvent -TransitionEvent -UIEvent -UIEvents interfaceName=UIEvent -WheelEvent -XMLHttpRequestProgressEvent -ApplePayCancelEvent conditional=APPLE_PAY -ApplePayCouponCodeChangedEvent conditional=APPLE_PAY_COUPON_CODE -ApplePayPaymentAuthorizedEvent conditional=APPLE_PAY -ApplePayPaymentMethodSelectedEvent conditional=APPLE_PAY -ApplePayShippingContactSelectedEvent conditional=APPLE_PAY -ApplePayShippingMethodSelectedEvent conditional=APPLE_PAY -ApplePayValidateMerchantEvent conditional=APPLE_PAY -AudioProcessingEvent conditional=WEB_AUDIO -BlobEvent conditional=MEDIA_RECORDER -OfflineAudioCompletionEvent conditional=WEB_AUDIO -MediaRecorderErrorEvent conditional=MEDIA_RECORDER -MediaStreamTrackEvent conditional=MEDIA_STREAM -MerchantValidationEvent conditional=PAYMENT_REQUEST -PaymentMethodChangeEvent conditional=PAYMENT_REQUEST -PaymentRequestUpdateEvent conditional=PAYMENT_REQUEST -RTCErrorEvent conditional=WEB_RTC -RTCPeerConnectionIceErrorEvent conditional=WEB_RTC -RTCPeerConnectionIceEvent conditional=WEB_RTC -RTCDataChannelEvent conditional=WEB_RTC -RTCDTMFToneChangeEvent conditional=WEB_RTC -RTCRtpSFrameTransformErrorEvent conditional=WEB_RTC -RTCTrackEvent conditional=WEB_RTC -RTCTransformEvent conditional=WEB_RTC -SpeechRecognitionErrorEvent -SpeechRecognitionEvent -SpeechSynthesisErrorEvent conditional=SPEECH_SYNTHESIS -SpeechSynthesisEvent conditional=SPEECH_SYNTHESIS -WebGLContextEvent conditional=WEBGL -StorageEvent -SVGEvents interfaceName=Event -SVGZoomEvent -SVGZoomEvents interfaceName=SVGZoomEvent -IDBVersionChangeEvent -TouchEvent conditional=TOUCH_EVENTS -DeviceMotionEvent conditional=DEVICE_ORIENTATION -DeviceOrientationEvent conditional=DEVICE_ORIENTATION -OrientationEvent interfaceName=Event, conditional=ORIENTATION_EVENTS -WebKitMediaKeyMessageEvent conditional=LEGACY_ENCRYPTED_MEDIA -WebKitMediaKeyNeededEvent conditional=LEGACY_ENCRYPTED_MEDIA -TrackEvent conditional=VIDEO -SecurityPolicyViolationEvent -GestureEvent conditional=IOS_GESTURE_EVENTS|MAC_GESTURE_EVENTS -WebKitPlaybackTargetAvailabilityEvent conditional=WIRELESS_PLAYBACK_TARGET -GamepadEvent conditional=GAMEPAD -OverconstrainedErrorEvent conditional=MEDIA_STREAM -MediaEncryptedEvent conditional=ENCRYPTED_MEDIA -MediaKeyMessageEvent conditional=ENCRYPTED_MEDIA -PointerEvent -PictureInPictureEvent conditional=PICTURE_IN_PICTURE_API -XRInputSourceEvent conditional=WEBXR -XRInputSourcesChangeEvent conditional=WEBXR -XRReferenceSpaceEvent conditional=WEBXR -XRSessionEvent conditional=WEBXR -NotificationEvent conditional=NOTIFICATION_EVENT diff --git a/src/jsc/bindings/webcore/JSTextEncoder.cpp b/src/jsc/bindings/webcore/JSTextEncoder.cpp index a82a257a86c9..9bf2e16173d2 100644 --- a/src/jsc/bindings/webcore/JSTextEncoder.cpp +++ b/src/jsc/bindings/webcore/JSTextEncoder.cpp @@ -63,62 +63,6 @@ extern "C" size_t TextEncoder__encodeInto8(const Latin1Character* stringPtr, siz extern "C" size_t TextEncoder__encodeInto16(const char16_t* stringPtr, size_t stringLen, void* ptr, size_t len); extern "C" JSC::EncodedJSValue TextEncoder__encodeRopeString(JSC::JSGlobalObject* lexicalGlobalObject, JSC::JSString* str); -template<> TextEncoder::EncodeIntoResult convertDictionary(JSGlobalObject& lexicalGlobalObject, JSValue value) -{ - auto& vm = JSC::getVM(&lexicalGlobalObject); - auto throwScope = DECLARE_THROW_SCOPE(vm); - bool isNullOrUndefined = value.isUndefinedOrNull(); - auto* object = isNullOrUndefined ? nullptr : value.getObject(); - if (!isNullOrUndefined && !object) [[unlikely]] { - throwTypeError(&lexicalGlobalObject, throwScope); - return {}; - } - TextEncoder::EncodeIntoResult result; - JSValue readValue; - if (isNullOrUndefined) - readValue = jsUndefined(); - else { - readValue = object->get(&lexicalGlobalObject, Identifier::fromString(vm, "read"_s)); - RETURN_IF_EXCEPTION(throwScope, {}); - } - if (!readValue.isUndefined()) { - result.read = convert(lexicalGlobalObject, readValue); - RETURN_IF_EXCEPTION(throwScope, {}); - } - JSValue writtenValue; - if (isNullOrUndefined) - writtenValue = jsUndefined(); - else { - writtenValue = object->get(&lexicalGlobalObject, Identifier::fromString(vm, "written"_s)); - RETURN_IF_EXCEPTION(throwScope, {}); - } - if (!writtenValue.isUndefined()) { - result.written = convert(lexicalGlobalObject, writtenValue); - RETURN_IF_EXCEPTION(throwScope, {}); - } - return result; -} - -JSC::JSObject* convertDictionaryToJS(JSC::JSGlobalObject& lexicalGlobalObject, JSDOMGlobalObject& globalObject, const TextEncoder::EncodeIntoResult& dictionary) -{ - auto& vm = JSC::getVM(&lexicalGlobalObject); - auto throwScope = DECLARE_THROW_SCOPE(vm); - - auto result = constructEmptyObject(&lexicalGlobalObject, globalObject.objectPrototype()); - - if (!IDLUnsignedLongLong::isNullValue(dictionary.read)) { - auto readValue = toJS(lexicalGlobalObject, throwScope, IDLUnsignedLongLong::extractValueFromNullable(dictionary.read)); - RETURN_IF_EXCEPTION(throwScope, {}); - result->putDirect(vm, JSC::Identifier::fromString(vm, "read"_s), readValue); - } - if (!IDLUnsignedLongLong::isNullValue(dictionary.written)) { - auto writtenValue = toJS(lexicalGlobalObject, throwScope, IDLUnsignedLongLong::extractValueFromNullable(dictionary.written)); - RETURN_IF_EXCEPTION(throwScope, {}); - result->putDirect(vm, JSC::Identifier::fromString(vm, "written"_s), writtenValue); - } - return result; -} - // Functions static JSC_DECLARE_HOST_FUNCTION(jsTextEncoderPrototypeFunction_encode); diff --git a/src/jsc/bindings/webcore/JSTextEncoder.h b/src/jsc/bindings/webcore/JSTextEncoder.h index 9775edeae63a..d6f2bd1d12cb 100644 --- a/src/jsc/bindings/webcore/JSTextEncoder.h +++ b/src/jsc/bindings/webcore/JSTextEncoder.h @@ -93,8 +93,4 @@ template<> struct JSDOMWrapperConverterTraits { using WrapperClass = JSTextEncoder; using ToWrappedReturnType = TextEncoder*; }; -template<> TextEncoder::EncodeIntoResult convertDictionary(JSC::JSGlobalObject&, JSC::JSValue); - -JSC::JSObject* convertDictionaryToJS(JSC::JSGlobalObject&, JSDOMGlobalObject&, const TextEncoder::EncodeIntoResult&); - } // namespace WebCore diff --git a/src/jsc/bindings/webcore/TextEncoder.cpp b/src/jsc/bindings/webcore/TextEncoder.cpp index 1942694cc983..ac85f55c15ca 100644 --- a/src/jsc/bindings/webcore/TextEncoder.cpp +++ b/src/jsc/bindings/webcore/TextEncoder.cpp @@ -35,40 +35,4 @@ String TextEncoder::encoding() const return "utf-8"_s; } -RefPtr TextEncoder::encode(String&& input) const -{ - // THIS CODE SHOULD NEVER BE REACHED IN BUN - RELEASE_ASSERT(1); - return nullptr; -} - -auto TextEncoder::encodeInto(String&& input, Ref&& array) -> EncodeIntoResult -{ - // THIS CODE SHOULD NEVER BE REACHED IN BUN - RELEASE_ASSERT(1); - - auto* destinationBytes = static_cast(array->baseAddress()); - auto capacity = array->byteLength(); - - uint64_t read = 0; - uint64_t written = 0; - - for (auto token : StringView(input).codePoints()) { - if (written >= capacity) { - ASSERT(written == capacity); - break; - } - UBool sawError = false; - U8_APPEND(destinationBytes, written, capacity, token, sawError); - if (sawError) - break; - if (U_IS_BMP(token)) - read++; - else - read += 2; - } - - return { read, written }; -} - } diff --git a/src/jsc/bindings/webcore/TextEncoder.h b/src/jsc/bindings/webcore/TextEncoder.h index 6a0145c78c25..5d43a6fcd081 100644 --- a/src/jsc/bindings/webcore/TextEncoder.h +++ b/src/jsc/bindings/webcore/TextEncoder.h @@ -24,8 +24,6 @@ #pragma once -#include "JSDOMConvertBufferSource.h" -#include #include #include #include @@ -37,15 +35,8 @@ namespace WebCore { class TextEncoder : public RefCounted { public: - struct EncodeIntoResult { - uint64_t read { 0 }; - uint64_t written { 0 }; - }; - static Ref create() { return adoptRef(*new TextEncoder); } String encoding() const; - RefPtr encode(String&&) const; - EncodeIntoResult encodeInto(String&&, Ref&& destination); private: TextEncoder() {}; diff --git a/src/jsc/bindings/webcore/streams/JSReadableStream.cpp b/src/jsc/bindings/webcore/streams/JSReadableStream.cpp index 007dc119037f..852d271cdc71 100644 --- a/src/jsc/bindings/webcore/streams/JSReadableStream.cpp +++ b/src/jsc/bindings/webcore/streams/JSReadableStream.cpp @@ -54,10 +54,6 @@ static JSC_DECLARE_CUSTOM_GETTER(jsReadableStreamPrototypeGetter_locked); static JSC_DECLARE_CUSTOM_GETTER(jsReadableStreamPrototypeGetter_constructor); static JSC_DECLARE_CUSTOM_GETTER(jsReadableStreamPrototype_nativePtrGetter); static JSC_DECLARE_CUSTOM_SETTER(jsReadableStreamPrototype_nativePtrSetter); -static JSC_DECLARE_CUSTOM_GETTER(jsReadableStreamPrototype_nativeTypeGetter); -static JSC_DECLARE_CUSTOM_SETTER(jsReadableStreamPrototype_nativeTypeSetter); -static JSC_DECLARE_CUSTOM_GETTER(jsReadableStreamPrototype_disturbedGetter); -static JSC_DECLARE_CUSTOM_SETTER(jsReadableStreamPrototype_disturbedSetter); static JSC_DECLARE_HOST_FUNCTION(jsReadableStreamPrototype_inspectCustom); class JSReadableStreamPrototype final : public JSC::JSNonFinalObject { @@ -426,11 +422,9 @@ void JSReadableStreamPrototype::finishCreation(VM& vm) JSValue valuesFunction = getDirect(vm, vm.propertyNames->builtinNames().valuesPublicName()); putDirectWithoutTransition(vm, vm.propertyNames->asyncIteratorSymbol, valuesFunction, static_cast(JSC::PropertyAttribute::DontEnum)); - // Bun private-name accessors read by surviving builtins (`stream.$bunNativePtr`, ...). + // Bun private-name accessor read by surviving builtins (`stream.$bunNativePtr`). auto& names = builtinNames(vm); putDirectCustomAccessor(vm, names.bunNativePtrPrivateName(), DOMAttributeGetterSetter::create(vm, jsReadableStreamPrototype_nativePtrGetter, jsReadableStreamPrototype_nativePtrSetter, DOMAttributeAnnotation { JSReadableStream::info(), nullptr }), JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute | JSC::PropertyAttribute::DontDelete); - putDirectCustomAccessor(vm, names.bunNativeTypePrivateName(), DOMAttributeGetterSetter::create(vm, jsReadableStreamPrototype_nativeTypeGetter, jsReadableStreamPrototype_nativeTypeSetter, DOMAttributeAnnotation { JSReadableStream::info(), nullptr }), JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute | JSC::PropertyAttribute::DontDelete); - putDirectCustomAccessor(vm, names.disturbedPrivateName(), DOMAttributeGetterSetter::create(vm, jsReadableStreamPrototype_disturbedGetter, jsReadableStreamPrototype_disturbedSetter, DOMAttributeAnnotation { JSReadableStream::info(), nullptr }), JSC::PropertyAttribute::CustomAccessor | JSC::PropertyAttribute::DOMAttribute | JSC::PropertyAttribute::DontDelete); Bun::WebStreams::installInspectCustom(vm, this, jsReadableStreamPrototype_inspectCustom); JSC_TO_STRING_TAG_WITHOUT_TRANSITION(); @@ -785,9 +779,9 @@ JSC_DEFINE_HOST_FUNCTION(jsReadableStreamPrototypeFunction_blob, (JSGlobalObject RELEASE_AND_RETURN(scope, JSValue::encode(readableStreamToBlob(lexicalGlobalObject, stream))); } -// Bun private-name accessors ($bunNativePtr / $bunNativeType / $disturbed). +// Bun private-name accessor ($bunNativePtr). // JSC brand-checks DOMAttribute getters (PropertySlot::customGetter) but invokes -// custom setters with any receiver inheriting the accessor, so each one validates +// custom setters with any receiver inheriting the accessor, so the setter validates // thisValue itself. JSC_DEFINE_CUSTOM_GETTER(jsReadableStreamPrototype_nativePtrGetter, (JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, PropertyName propertyName)) @@ -814,52 +808,4 @@ JSC_DEFINE_CUSTOM_SETTER(jsReadableStreamPrototype_nativePtrSetter, (JSGlobalObj return true; } -JSC_DEFINE_CUSTOM_GETTER(jsReadableStreamPrototype_nativeTypeGetter, (JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, PropertyName propertyName)) -{ - auto& vm = JSC::getVM(lexicalGlobalObject); - auto scope = DECLARE_THROW_SCOPE(vm); - const auto* stream = dynamicDowncast(JSValue::decode(thisValue)); - if (!stream) [[unlikely]] - return throwVMDOMAttributeGetterTypeError(lexicalGlobalObject, scope, JSReadableStream::info(), propertyName); - return JSValue::encode(jsNumber(stream->m_nativeType)); -} - -JSC_DEFINE_CUSTOM_SETTER(jsReadableStreamPrototype_nativeTypeSetter, (JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, JSC::EncodedJSValue encodedValue, PropertyName propertyName)) -{ - auto& vm = JSC::getVM(lexicalGlobalObject); - auto scope = DECLARE_THROW_SCOPE(vm); - auto* stream = dynamicDowncast(JSValue::decode(thisValue)); - if (!stream) [[unlikely]] { - throwDOMAttributeSetterTypeError(lexicalGlobalObject, scope, JSReadableStream::info(), propertyName); - return false; - } - int32_t nativeType = JSValue::decode(encodedValue).toInt32(lexicalGlobalObject); - RETURN_IF_EXCEPTION(scope, false); - stream->m_nativeType = nativeType; - return true; -} - -JSC_DEFINE_CUSTOM_GETTER(jsReadableStreamPrototype_disturbedGetter, (JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, PropertyName propertyName)) -{ - auto& vm = JSC::getVM(lexicalGlobalObject); - auto scope = DECLARE_THROW_SCOPE(vm); - const auto* stream = dynamicDowncast(JSValue::decode(thisValue)); - if (!stream) [[unlikely]] - return throwVMDOMAttributeGetterTypeError(lexicalGlobalObject, scope, JSReadableStream::info(), propertyName); - return JSValue::encode(jsBoolean(stream->m_disturbed)); -} - -JSC_DEFINE_CUSTOM_SETTER(jsReadableStreamPrototype_disturbedSetter, (JSGlobalObject * lexicalGlobalObject, JSC::EncodedJSValue thisValue, JSC::EncodedJSValue encodedValue, PropertyName propertyName)) -{ - auto& vm = JSC::getVM(lexicalGlobalObject); - auto scope = DECLARE_THROW_SCOPE(vm); - auto* stream = dynamicDowncast(JSValue::decode(thisValue)); - if (!stream) [[unlikely]] { - throwDOMAttributeSetterTypeError(lexicalGlobalObject, scope, JSReadableStream::info(), propertyName); - return false; - } - stream->m_disturbed = JSValue::decode(encodedValue).toBoolean(lexicalGlobalObject); - return true; -} - } // namespace WebCore diff --git a/src/jsc/bindings/webcore/streams/JSReadableStream.h b/src/jsc/bindings/webcore/streams/JSReadableStream.h index ea047660d42f..59248ac29759 100644 --- a/src/jsc/bindings/webcore/streams/JSReadableStream.h +++ b/src/jsc/bindings/webcore/streams/JSReadableStream.h @@ -54,8 +54,6 @@ class JSReadableStream final : public JSC::JSNonFinalObject { ControllerKind m_controllerKind { ControllerKind::None }; // [[disturbed]] bool m_disturbed : 1 { false }; - // [[Detached]] (transferable streams are not implemented; the slot exists) - bool m_detached : 1 { false }; // Bun: locked by a native/direct consumer WITHOUT a real reader object. Part of every // isReadableStreamLocked() check. bool m_lockedWithoutReader : 1 { false }; @@ -66,8 +64,6 @@ class JSReadableStream final : public JSC::JSNonFinalObject { // Body.textStream(): the native source adapter decodes each chunk as UTF-8 // text before enqueue. bool m_nativeTextMode : 1 { false }; - // `$bunNativeType`: write-only today, kept for the FFI ABI. - int32_t m_nativeType { 0 }; // [[reader]] — a default reader, a BYOB reader, or null (undefined). JSC::WriteBarrier m_reader; diff --git a/src/jsc/bindings/webcore/streams/JSTransformStream.h b/src/jsc/bindings/webcore/streams/JSTransformStream.h index cd11ee34ef78..cfb21bcf7131 100644 --- a/src/jsc/bindings/webcore/streams/JSTransformStream.h +++ b/src/jsc/bindings/webcore/streams/JSTransformStream.h @@ -53,8 +53,6 @@ class JSTransformStream : public JSC::JSNonFinalObject { // [[backpressure]] — InitializeTransformStream sets it (to true) before anything reads it, // so the spec's initial "undefined" state needs no separate representation. bool m_backpressure : 1 { false }; - // [[Detached]] (transferable streams are not implemented; the slot exists) - bool m_detached : 1 { false }; // Native transform/flush arm is on the stack (coder pointer live); a re-entrant // ClearAlgorithms defers the eager free to the arm's epilogue instead. bool m_nativeStateInUse : 1 { false }; diff --git a/src/jsc/bindings/webcore/streams/JSWritableStream.h b/src/jsc/bindings/webcore/streams/JSWritableStream.h index 1e62dd9fa2dc..2108849441fa 100644 --- a/src/jsc/bindings/webcore/streams/JSWritableStream.h +++ b/src/jsc/bindings/webcore/streams/JSWritableStream.h @@ -87,8 +87,6 @@ class JSWritableStream final : public JSC::JSDestructibleObject { WritableStreamState m_state { WritableStreamState::Writable }; // [[backpressure]] bool m_backpressure : 1 { false }; - // [[Detached]] (transferable streams are not implemented; the slot exists) - bool m_detached : 1 { false }; private: JSWritableStream(JSC::VM&, JSC::Structure*); diff --git a/src/jsc/bindings/webcore/streams/WebStreamsExports.cpp b/src/jsc/bindings/webcore/streams/WebStreamsExports.cpp index 1b565593fc3b..eee940946fed 100644 --- a/src/jsc/bindings/webcore/streams/WebStreamsExports.cpp +++ b/src/jsc/bindings/webcore/streams/WebStreamsExports.cpp @@ -192,7 +192,6 @@ extern "C" void ReadableStream__detach(JSC::EncodedJSValue possibleReadableStrea if (!stream) [[unlikely]] return; stream->m_nativePtr.set(globalObject->vm(), stream, jsNumber(-1)); - stream->m_nativeType = 0; stream->m_disturbed = true; } diff --git a/src/jsc/bindings/webcrypto/CryptoKeyOKP.cpp b/src/jsc/bindings/webcrypto/CryptoKeyOKP.cpp index 806bd09d4fd9..99ad463232d8 100644 --- a/src/jsc/bindings/webcrypto/CryptoKeyOKP.cpp +++ b/src/jsc/bindings/webcrypto/CryptoKeyOKP.cpp @@ -232,15 +232,7 @@ auto CryptoKeyOKP::algorithm() const -> KeyAlgorithm // FIXME: This should be set to the actual algorithm name in the case of X25519 result.name = CryptoAlgorithmRegistry::singleton().name(algorithmIdentifier()); - // This is commented out because the spec doesn't define the namedCurve field for OKP keys - // switch (m_curve) { - // case NamedCurve::X25519: - // result.namedCurve = X25519; - // break; - // case NamedCurve::Ed25519: - // result.namedCurve = Ed25519; - // break; - // } + // The spec doesn't define the namedCurve field for OKP keys. return result; } diff --git a/src/lsquic_sys/lib.rs b/src/lsquic_sys/lib.rs index 11894e7021cb..bd2aa1003936 100644 --- a/src/lsquic_sys/lib.rs +++ b/src/lsquic_sys/lib.rs @@ -45,8 +45,6 @@ pub const LSCONN_ST_RESET: c_int = 5; pub const LSCONN_ST_ERROR: c_int = 7; pub const LSCONN_ST_VERNEG_FAILURE: c_int = 10; -pub const LSQVER_I001: c_int = 5; -pub const LSQVER_I002: c_int = 6; pub const N_LSQVER: c_int = 8; pub const LSQUIC_GLOBAL_CLIENT: c_int = 1; @@ -160,7 +158,6 @@ unsafe extern "C" { pub fn lsquic_conn_status(c: *mut lsquic_conn, errbuf: *mut c_char, bufsz: usize) -> c_int; pub fn lsquic_conn_make_stream(c: *mut lsquic_conn); pub fn lsquic_conn_make_uni_stream(c: *mut lsquic_conn); - pub fn lsquic_conn_n_avail_streams(c: *const lsquic_conn) -> c_uint; pub fn lsquic_conn_n_pending_streams(c: *const lsquic_conn) -> c_uint; pub fn lsquic_conn_get_sockaddr( c: *mut lsquic_conn, @@ -381,110 +378,6 @@ settings_setters! { delay_onclose => us_nq_settings_set_delay_onclose : c_int, } -pub struct Engine(*mut lsquic_engine); - -impl Engine { - /// `vtable` and `alpn` must outlive the returned engine — lsquic stores both pointers. - pub fn new( - is_server: bool, - is_http: bool, - vtable: &NqVtable, - settings: &Settings, - alpn: Option<&[u8]>, - ) -> Option { - // SAFETY: settings is a live struct lsquic copies; alpn is - // caller-guaranteed to outlive the engine. - let raw = unsafe { - us_nq_engine_new( - is_server as c_int, - is_http as c_int, - core::ptr::from_ref(vtable).cast_mut(), - settings.as_ptr(), - alpn.map_or(core::ptr::null(), |a| a.as_ptr().cast()), - ) - }; - (!raw.is_null()).then_some(Self(raw)) - } - - /// # Safety - /// `local`/`peer` must point to valid sockaddrs for the duration of the - /// call, and `peer_ctx` must be the pointer the engine was configured with. - pub unsafe fn packet_in( - &self, - data: &[u8], - local: *const sockaddr, - peer: *const sockaddr, - peer_ctx: *mut c_void, - ) -> c_int { - // SAFETY: `self.0` is live; `data` is a slice; the sockaddrs are - // caller-guaranteed valid for this call (lsquic copies them). - unsafe { - lsquic_engine_packet_in(self.0, data.as_ptr(), data.len(), local, peer, peer_ctx, 0) - } - } - - pub fn process_conns(&self) { - // SAFETY: `self.0` is live. - unsafe { lsquic_engine_process_conns(self.0) } - } - - pub fn earliest_adv_tick(&self) -> Option { - let mut diff: c_int = 0; - // SAFETY: `self.0` is live; `diff` is a stack out-param. - if unsafe { lsquic_engine_earliest_adv_tick(self.0, core::ptr::from_mut(&mut diff)) } != 0 { - Some(diff) - } else { - None - } - } - - /// # Safety - /// `local`/`peer` must point to valid sockaddrs for the duration of the - /// call; `peer_ctx`/`conn_ctx` must stay valid for the connection's life. - #[allow(clippy::too_many_arguments)] - pub unsafe fn connect( - &self, - local: *const sockaddr, - peer: *const sockaddr, - peer_ctx: *mut c_void, - conn_ctx: *mut c_void, - sni: Option<&[u8]>, - sess_resume: Option<&[u8]>, - token: Option<&[u8]>, - ) -> Option { - // SAFETY: `self.0` is live; the sockaddrs/peer_ctx/conn_ctx are - // caller-guaranteed valid for this call. lsquic copies sni/sess/token. - let raw = unsafe { - lsquic_engine_connect( - self.0, - N_LSQVER, - local, - peer, - peer_ctx, - conn_ctx, - sni.map_or(core::ptr::null(), |s| s.as_ptr().cast()), - 0, - sess_resume.map_or(core::ptr::null(), |s| s.as_ptr()), - sess_resume.map_or(0, |s| s.len()), - token.map_or(core::ptr::null(), |t| t.as_ptr()), - token.map_or(0, |t| t.len()), - ) - }; - (!raw.is_null()).then_some(Conn(raw)) - } - - pub fn raw(&self) -> *mut lsquic_engine { - self.0 - } -} - -impl Drop for Engine { - fn drop(&mut self) { - // SAFETY: `self.0` was returned by `us_nq_engine_new` and not freed. - unsafe { lsquic_engine_destroy(self.0) } - } -} - /// Borrowed `lsquic_conn_t`. lsquic owns the conn and frees it after /// `on_conn_closed` returns; callers must not hold a `Conn` past that point. #[derive(Copy, Clone)] @@ -497,9 +390,6 @@ impl Conn { pub unsafe fn from_raw(raw: *mut lsquic_conn) -> Option { (!raw.is_null()).then_some(Self(raw)) } - pub fn raw(&self) -> *mut lsquic_conn { - self.0 - } pub fn close(&self) { // SAFETY: `self.0` is live (caller contract). unsafe { lsquic_conn_close(self.0) } @@ -534,16 +424,6 @@ impl Conn { v => Some(v != 0), } } - /// # Safety - /// `ctx` must outlive the connection (lsquic stores it verbatim). - pub unsafe fn set_ctx(&self, ctx: *mut c_void) { - // SAFETY: as above. - unsafe { lsquic_conn_set_ctx(self.0, ctx) } - } - pub fn ctx(&self) -> *mut c_void { - // SAFETY: as above. - unsafe { lsquic_conn_get_ctx(self.0) } - } pub fn make_stream(&self) { // SAFETY: as above. unsafe { lsquic_conn_make_stream(self.0) } @@ -552,10 +432,6 @@ impl Conn { // SAFETY: as above. unsafe { lsquic_conn_make_uni_stream(self.0) } } - pub fn n_avail_streams(&self) -> u32 { - // SAFETY: as above. - unsafe { lsquic_conn_n_avail_streams(self.0) } - } pub fn want_datagram_write(&self, want: bool) -> c_int { // SAFETY: as above. unsafe { lsquic_conn_want_datagram_write(self.0, want as c_int) } @@ -613,27 +489,6 @@ impl Conn { // SAFETY: as above. unsafe { lsquic_conn_get_ssl(self.0) } } - pub fn sockaddr(&self) -> Option<(*const sockaddr, *const sockaddr)> { - let mut local: *const sockaddr = core::ptr::null(); - let mut peer: *const sockaddr = core::ptr::null(); - // SAFETY: as above; out-params are stack slots. - if unsafe { - lsquic_conn_get_sockaddr( - self.0, - core::ptr::from_mut(&mut local), - core::ptr::from_mut(&mut peer), - ) - } == 0 - { - Some((local, peer)) - } else { - None - } - } - pub fn status(&self, buf: &mut [c_char]) -> c_int { - // SAFETY: as above; `buf` is a live slice. - unsafe { lsquic_conn_status(self.0, buf.as_mut_ptr(), buf.len()) } - } } /// Borrowed `lsquic_stream_t`. Same lifetime contract as [`Conn`] — invalid @@ -830,16 +685,6 @@ impl Drop for HeaderSet { } } -pub fn global_init() { - // SAFETY: pure library init. - unsafe { lsquic_global_init(LSQUIC_GLOBAL_CLIENT | LSQUIC_GLOBAL_SERVER) }; -} - -pub fn enable_logging(level: &core::ffi::CStr) { - // SAFETY: `level` is a NUL-terminated string. - unsafe { us_nq_enable_logging(level.as_ptr()) } -} - /// Mirrors `struct lsquic_conn_info` (lsquic.h). #[repr(C)] #[derive(Default)] diff --git a/src/runtime/api/BunObject.rs b/src/runtime/api/BunObject.rs index fdedb2be588f..4c3d377b8f57 100644 --- a/src/runtime/api/BunObject.rs +++ b/src/runtime/api/BunObject.rs @@ -1231,41 +1231,6 @@ fn resolve(global_object: &JSGlobalObject, callframe: &CallFrame) -> JsResult JSValue { - let Ok(specifier_str) = specifier.to_bun_string(global) else { - return JSValue::ZERO; - }; - let specifier_str = scopeguard::guard(specifier_str, |s| s.deref()); - - let Ok(source_str) = source.to_bun_string(global) else { - return JSValue::ZERO; - }; - let source_str = scopeguard::guard(source_str, |s| s.deref()); - - let value = match do_resolve_with_args::( - global, - *specifier_str, - *source_str, - ResolveMode::from_ffi_bools(is_esm, false), - ) { - Ok(v) => v, - Err(_) => { - let err = global.try_take_exception().unwrap(); - return JSPromise::dangerously_create_rejected_promise_value_without_notifying_vm( - global, err, - ); - } - }; - - JSPromise::resolved_promise_value(global, value) -} - // HOST_EXPORT(Bun__resolveSync, c) pub fn bun_resolve_sync( global: &JSGlobalObject, diff --git a/src/runtime/bake/client/JavaScriptSyntaxHighlighter.css b/src/runtime/bake/client/JavaScriptSyntaxHighlighter.css deleted file mode 100644 index 3cd872204a3a..000000000000 --- a/src/runtime/bake/client/JavaScriptSyntaxHighlighter.css +++ /dev/null @@ -1,147 +0,0 @@ -/* Dracula Syntax Highlighting Theme */ -:root { - --dracula-background: #282a36; - --dracula-foreground: #f8f8f2; - --dracula-comment: #6272a4; - --dracula-cyan: #8be9fd; - --dracula-green: #50fa7b; - --dracula-orange: #ffb86c; - --dracula-pink: #ff79c6; - --dracula-purple: #bd93f9; - --dracula-red: #ff5555; - --dracula-yellow: #f1fa8c; - --dracula-selection: #44475a; - --dracula-current-line: #44475a20; - --gutter-width: 2rem; - --gutter-padding: 0.5rem; -} - -pre, -code { - background-color: var(--dracula-background); - color: var(--dracula-foreground); - margin: 0; - padding: 1rem; - font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; - font-size: 14px; - line-height: 1.4; - tab-size: 2; - white-space: pre; -} - -pre { - overflow-x: auto; - position: relative; -} - -/* Line number support */ -.dracula-theme.with-line-numbers { - counter-reset: line; - padding-left: var(--gutter-width); -} - -.dracula-theme.with-line-numbers .line { - counter-increment: line; - position: relative; - vertical-align: bottom; - padding-left: var(--gutter-padding); - white-space: pre; -} - -.dracula-theme.with-line-numbers .line::before { - content: counter(line); - position: absolute; - left: calc(-1 * var(--gutter-width)); - width: var(--gutter-width); - height: 100%; - border-right: 1px solid var(--dracula-selection); - padding-right: var(--gutter-padding); - color: var(--dracula-comment); - text-align: right; - font-size: 12px; - user-select: none; - background-color: var(--dracula-background); - font-variant-numeric: tabular-nums; -} - -.dracula-theme.with-line-numbers .line:hover { - background-color: var(--dracula-current-line); -} - -/* Token classes mapped to Dracula spec */ -.syntax-pink { - color: var(--dracula-pink); -} - -.syntax-cyan { - color: var(--dracula-cyan); -} - -.syntax-orange { - color: var(--dracula-orange); -} - -.syntax-red { - color: var(--dracula-red); -} - -.syntax-green { - color: var(--dracula-green); -} - -.syntax-yellow { - color: var(--dracula-yellow); -} - -.syntax-gray { - color: var(--dracula-comment); -} - -.syntax-purple { - color: var(--dracula-purple); -} - -.syntax-fg { - color: var(--dracula-foreground); -} - -/* Style modifiers */ -.italic { - font-style: italic; -} - -.bold { - font-weight: bold; -} - -/* Combined token classes */ -.syntax-cyan.italic { - color: var(--dracula-cyan); - font-style: italic; -} - -.syntax-orange.italic { - color: var(--dracula-orange); - font-style: italic; -} - -.syntax-green.italic { - color: var(--dracula-green); - font-style: italic; -} - -.syntax-pink.bold { - color: var(--dracula-pink); - font-weight: bold; -} - -/* Template literals and interpolation */ -.syntax-yellow .interpolation { - color: var(--dracula-pink); -} - -/* Ensure proper contrast on selection */ -::selection { - background-color: var(--dracula-selection); - color: var(--dracula-foreground); -} diff --git a/src/runtime/bake/client/JavaScriptSyntaxHighlighterComponent.tsx b/src/runtime/bake/client/JavaScriptSyntaxHighlighterComponent.tsx deleted file mode 100644 index dfcfbbeddd96..000000000000 --- a/src/runtime/bake/client/JavaScriptSyntaxHighlighterComponent.tsx +++ /dev/null @@ -1,41 +0,0 @@ -// This code isn't actually used by the client -// It exists so we can visually see the syntax highlighter in action -import { DraculaSyntaxHighlighter } from "./JavaScriptSyntaxHighlighter"; -import "./JavaScriptSyntaxHighlighter.css"; - -interface SyntaxHighlighterProps { - code: string; - language?: string; - showLineNumbers?: boolean; - redactSensitiveInformation?: boolean; - className?: string; - style?: React.CSSProperties; -} - -export const SyntaxHighlighter: React.FC = ({ - code, - language = "javascript", - showLineNumbers = true, - redactSensitiveInformation = false, - className = "", - style = {}, -}) => { - // Create a new instance of the highlighter - const highlighter = new DraculaSyntaxHighlighter(code, { - enableColors: true, - redactSensitiveInformation, - languageName: language, - showLineNumbers, - }); - - // Get the highlighted HTML - const highlightedCode = highlighter.highlight(); - - return ( -
- ); -}; diff --git a/src/runtime/ffi/libtcc1.a.macos-aarch64 b/src/runtime/ffi/libtcc1.a.macos-aarch64 deleted file mode 100644 index 60696b61176e..000000000000 Binary files a/src/runtime/ffi/libtcc1.a.macos-aarch64 and /dev/null differ diff --git a/src/runtime/node/node_os.rs b/src/runtime/node/node_os.rs index ccff60e67c66..a3d49aafa5e6 100644 --- a/src/runtime/node/node_os.rs +++ b/src/runtime/node/node_os.rs @@ -29,7 +29,7 @@ pub(crate) fn freemem() -> u64 { // ─── gated: JSC bindings + platform syscall bodies ──────────────────────── // Every fn body builds JS objects (`JSValue::create_*`, `ZigString::*::to_js`, -// `global.throw_value`) or reaches `bun_sys::posix::sysctlbyname` / +// `global.throw_value`) or reaches `bun_sys::posix::sysctl_read*` / // `bun_sys::c::sysinfo` / `crate::gen_::node_os` which are not yet exported. // CPUTimes struct + freemem() + trailing pure helpers hoisted above/below. diff --git a/src/spawn_sys/spawn_process.rs b/src/spawn_sys/spawn_process.rs index 3cd940e230c3..65a2f2807285 100644 --- a/src/spawn_sys/spawn_process.rs +++ b/src/spawn_sys/spawn_process.rs @@ -12,7 +12,9 @@ use core::sync::atomic::Ordering; #[cfg(target_os = "macos")] use bun_core::Output; -use bun_sys::{self, Fd, FdExt as _}; +#[cfg(unix)] +use bun_sys::FdExt as _; +use bun_sys::{self, Fd}; #[cfg(not(windows))] use crate::posix_spawn::posix_spawn; @@ -494,17 +496,6 @@ impl ExtraPipe { } impl PosixSpawnResult { - pub fn close(&mut self) { - for item in self.extra_pipes.iter() { - match item { - ExtraPipe::OwnedFd(f) => f.close(), - ExtraPipe::UnownedFd(_) | ExtraPipe::Unavailable => {} - } - } - self.extra_pipes.clear(); - self.extra_pipes.shrink_to_fit(); - } - #[cfg(any(target_os = "linux", target_os = "android"))] fn pidfd_flags_for_linux() -> u32 { // PIDFD_NONBLOCK is only supported on kernel 5.10+ (the EINVAL retry @@ -581,14 +572,6 @@ impl PosixSpawnResult { Ok(fd) => Ok(fd.native()), } } - - #[cfg(not(any(target_os = "linux", target_os = "android")))] - pub fn pifd_from_pid(&mut self) -> bun_sys::Result { - Err(bun_sys::Error::from_code( - bun_sys::E::ENOSYS, - bun_sys::Tag::pidfd_open, - )) - } } // ────────────────────────────────────────────────────────────────────────── diff --git a/src/sys/lib.rs b/src/sys/lib.rs index c2e8b81781c7..715452b4c6ff 100644 --- a/src/sys/lib.rs +++ b/src/sys/lib.rs @@ -214,12 +214,6 @@ pub mod dir_iterator { // `borrow()` debug_assert. unsafe { bun_core::ZStr::from_raw(self.ptr.as_ptr(), self.len) } } - #[cfg(windows)] - #[inline] - pub fn as_zstr(&self) -> &bun_core::WStr { - // `from_slice` pushed a trailing NUL. - bun_core::WStr::from_slice_with_nul(&self.native) - } } // 8-byte alignment matches `@alignOf(linux.dirent64)` / Darwin dirent / @@ -1315,6 +1309,7 @@ impl Tag { pub const fstatat: Tag = Tag(17); pub const fsync: Tag = Tag(18); pub(crate) const ftruncate: Tag = Tag(19); + #[cfg(not(windows))] pub(crate) const futimens: Tag = Tag(20); pub const getdents64: Tag = Tag(21); pub const getdirentries64: Tag = Tag(22); @@ -1575,9 +1570,6 @@ mod safe_libc { pub(crate) safe fn dup2(old: c_int, new: c_int) -> c_int; pub(crate) safe fn isatty(fd: c_int) -> c_int; pub(crate) safe fn fsync(fd: c_int) -> c_int; - // macOS has had fdatasync(2) since 10.7; the `libc` crate omits the - // Apple binding, so a local decl is needed there anyway. - pub(crate) safe fn fdatasync(fd: c_int) -> c_int; pub(crate) safe fn fchdir(fd: c_int) -> c_int; pub(crate) safe fn umask(mode: libc::mode_t) -> libc::mode_t; pub(crate) safe fn fchmod(fd: c_int, mode: libc::mode_t) -> c_int; @@ -2679,15 +2671,6 @@ mod posix_impl { } // ── link/perm/time/access group ── - pub fn link(src: &ZStr, dest: &ZStr) -> Maybe<()> { - check_p!( - // SAFETY: both `ZStr`s are valid NUL-terminated C strings. - unsafe { libc::link(src.as_ptr(), dest.as_ptr()) }, - Tag::link, - src - ); - Ok(()) - } pub fn linkat(src_dir: impl AsFd, src: &ZStr, dest_dir: impl AsFd, dest: &ZStr) -> Maybe<()> { let src_dir = src_dir.as_fd(); let dest_dir = dest_dir.as_fd(); @@ -3063,13 +3046,6 @@ mod posix_impl { check!(safe_libc::fsync(fd.native()), Tag::fsync); Ok(()) } - pub fn fdatasync(fd: Fd) -> Maybe<()> { - // `fdatasync` is available on all Unix - // (macOS has had fdatasync(2) since 10.7). The libc crate omits the - // Apple binding; `safe_libc::fdatasync` declares it locally. - check!(safe_libc::fdatasync(fd.native()), Tag::fdatasync); - Ok(()) - } pub fn lseek(fd: Fd, offset: i64, whence: i32) -> Maybe { let rc = check!(safe_libc::lseek(fd.native(), offset, whence), Tag::lseek); Ok(rc) @@ -3541,11 +3517,6 @@ mod posix_impl { return Ok(rc as usize); } } - #[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))] - pub fn sendfile(src: Fd, _dest: Fd, _len: usize) -> Maybe { - // Attach the *source* fd. - Err(Error::from_code_int(libc::ENOSYS, Tag::sendfile).with_fd(src)) - } } #[cfg(unix)] pub use posix_impl::*; @@ -3920,9 +3891,6 @@ mod windows_impl { pub fn fchmod(fd: Fd, mode: Mode) -> Maybe<()> { sys_uv::fchmod(fd, mode) } - pub fn fchown(fd: Fd, uid: u32, gid: u32) -> Maybe<()> { - sys_uv::fchown(fd, uid as _, gid as _) - } pub fn ftruncate(fd: Fd, len: i64) -> Maybe<()> { // Calls `NtSetInformationFile(.., // FileEndOfFileInformation)` directly on the HANDLE (NOT via libuv — @@ -3949,21 +3917,6 @@ mod windows_impl { } Ok(()) } - pub fn chmod(path: &ZStr, mode: Mode) -> Maybe<()> { - sys_uv::chmod(path, mode) - } - pub fn chown(path: &ZStr, uid: u32, gid: u32) -> Maybe<()> { - sys_uv::chown(path, uid as _, gid as _) - } - pub fn link(src: &ZStr, dest: &ZStr) -> Maybe<()> { - sys_uv::link(src, dest) - } - pub fn fsync(fd: Fd) -> Maybe<()> { - sys_uv::fsync(fd) - } - pub fn fdatasync(fd: Fd) -> Maybe<()> { - sys_uv::fdatasync(fd) - } // ── kernel32 / ntdll arms ──────────────────────────────────────────── pub fn openat(dir: impl AsFd, path: &ZStr, flags: i32, mode: Mode) -> Maybe { @@ -4213,26 +4166,6 @@ mod windows_impl { } }) } - pub fn linkat(src_dir: impl AsFd, src: &ZStr, dest_dir: impl AsFd, dest: &ZStr) -> Maybe<()> { - let src_dir = src_dir.as_fd(); - let dest_dir = dest_dir.as_fd(); - // No native `linkat` on Windows — resolve to absolute and CreateHardLinkW. - let mut sb = bun_core::PathBuffer::default(); - let mut db = bun_core::PathBuffer::default(); - let s = super::get_fd_path(src_dir, &mut sb)?; - let d = super::get_fd_path(dest_dir, &mut db)?; - let mut sj = bun_core::PathBuffer::default(); - let mut dj = bun_core::PathBuffer::default(); - let s_abs = bun_paths::resolve_path::join_string_buf_z::( - &mut sj.0, - &[s, src.as_bytes()], - ); - let d_abs = bun_paths::resolve_path::join_string_buf_z::( - &mut dj.0, - &[d, dest.as_bytes()], - ); - link(s_abs, d_abs) - } pub(crate) fn linkat_tmpfile(_tmpfd: Fd, _dirfd: Fd, _name: &ZStr) -> Maybe<()> { Err(Error::new(E::ENOTSUP, Tag::link)) } @@ -4260,25 +4193,6 @@ mod windows_impl { ); readlink(abs, buf) } - pub fn fchmodat(dir: impl AsFd, path: &ZStr, mode: Mode, _flags: i32) -> Maybe<()> { - let dir = dir.as_fd(); - let mut db = bun_core::PathBuffer::default(); - let d = super::get_fd_path(dir, &mut db)?; - let mut dj = bun_core::PathBuffer::default(); - let abs = bun_paths::resolve_path::join_string_buf_z::( - &mut dj.0, - &[d, path.as_bytes()], - ); - chmod(abs, mode) - } - pub fn lchmod(path: &ZStr, mode: Mode) -> Maybe<()> { - // Windows has no lchmod; libuv chmod follows symlinks. Match Node: fall through. - chmod(path, mode) - } - pub fn lchown(path: &ZStr, uid: u32, gid: u32) -> Maybe<()> { - // Windows has no ownership model; libuv uv_fs_lchown is a no-op success. - sys_uv::lchown(path, uid as _, gid as _) - } pub fn fstatat(fd: impl AsFd, path: &ZStr) -> Maybe { let fd = fd.as_fd(); // `openat(fd, path, 0, 0)` (flags=0 @@ -4332,19 +4246,6 @@ mod windows_impl { Err(_) => Ok(false), } } - pub fn futimens(fd: Fd, atime: TimeLike, mtime: TimeLike) -> Maybe<()> { - // `uv_fs_futime` takes a CRT fd (`fd.uv()` PANICS for HANDLE-backed - // `FdKind::System` fds); `SetFileTime` operates on the HANDLE - // directly. `fd.native()` yields the HANDLE for both kinds. - let a = w::timespec_to_filetime(atime); - let m = w::timespec_to_filetime(mtime); - // SAFETY: FFI; `fd.native()` is a valid HANDLE, `a`/`m` valid for read. - let rc = unsafe { w::kernel32::SetFileTime(fd.native(), core::ptr::null(), &a, &m) }; - if rc == 0 { - return Err(Error::new(w::get_last_errno(), Tag::futimens).with_fd(fd)); - } - Ok(()) - } pub fn utimens(path: &ZStr, atime: TimeLike, mtime: TimeLike) -> Maybe<()> { let a = atime.sec as f64 + atime.nsec as f64 / 1e9; let m = mtime.sec as f64 + mtime.nsec as f64 / 1e9; @@ -4369,27 +4270,6 @@ mod windows_impl { } Ok(()) } - pub fn lutimens(path: &ZStr, atime: TimeLike, mtime: TimeLike) -> Maybe<()> { - let a = atime.sec as f64 + atime.nsec as f64 / 1e9; - let m = mtime.sec as f64 + mtime.nsec as f64 / 1e9; - let mut req = uv::fs_t::uninitialized(); - let rc = unsafe { - uv::uv_fs_lutime( - core::ptr::null_mut(), - &mut req, - path.as_ptr().cast::<_>(), - a, - m, - None, - ) - }; - // Same fs__capture_path leak as utimens. - req.deinit(); - if let Some(err) = Error::from_uv_rc(rc, Tag::lutime) { - return Err(err.with_path(path.as_bytes())); - } - Ok(()) - } pub fn exists_z(path: &ZStr) -> bool { // GetFileAttributesW != INVALID. access(path, 0).is_ok() @@ -4436,9 +4316,6 @@ mod windows_impl { // get_fd_path yields `&mut [u8]`; coerce to shared. r.map(|s| &*s) } - pub fn fcntl(_fd: Fd, _cmd: i32, _arg: isize) -> Maybe { - Err(Error::new(E::ENOTSUP, Tag::fcntl)) - } pub fn pipe() -> Maybe<[Fd; 2]> { // uv_pipe(fds, 0, 0). let mut fds: [uv::uv_file; 2] = [-1, -1]; @@ -4540,10 +4417,6 @@ mod windows_impl { pub fn send_non_block(fd: Fd, buf: &[u8]) -> Maybe { send(fd, buf, 0) } - pub fn socketpair(_domain: i32, _ty: i32, _proto: i32, _nonblock: bool) -> Maybe<[Fd; 2]> { - // Use spawnIPCSocket on Windows instead. - Err(Error::new(E::ENOTSUP, Tag::socketpair)) - } pub fn mmap( _addr: *mut u8, _len: usize, @@ -4557,17 +4430,6 @@ mod windows_impl { pub fn munmap(_ptr: *mut u8, _len: usize) -> Maybe<()> { Err(Error::new(E::ENOTSUP, Tag::munmap)) } - pub fn sendfile(src: Fd, _dest: Fd, _len: usize) -> Maybe { - // `bun.sys.sendfile` is Linux-only - // (`sendfile(2)` with a *null* offset so the kernel advances - // the source fd's file position). An earlier implementation called - // `uv_fs_sendfile(..., in_offset=0, ...)`, which (a) re-reads byte 0 - // on every iteration of a chunked copy loop and (b) returned the int - // rc (always `0` on success) instead of `req.result`. Surface ENOSYS - // so callers fall back to the read/write copy loop, matching the - // non-Linux posix arm above. - Err(Error::new(E::ENOSYS, Tag::sendfile).with_fd(src)) - } pub type FcntlInt = isize; pub const MSG_DONTWAIT: i32 = 0; pub const SEND_FLAGS_NONBLOCK: i32 = 0; @@ -5125,9 +4987,6 @@ pub mod c { target_os = "openbsd" ))] pub use libc::{getloadavg, sockaddr_dl, sysctlbyname}; - #[cfg(windows)] - #[allow(non_camel_case_types)] - pub type fd_t = bun_core::FdNative; /// libc `dlsym` (RTLD_DEFAULT when `handle` is null). #[cfg(unix)] @@ -5293,27 +5152,6 @@ pub mod c { dyld_get_image_header_raw(image_index).cast() } - /// `bun.c.kqueue` — create a new kqueue fd. - #[cfg(any(target_os = "macos", target_os = "freebsd"))] - #[inline] - pub fn kqueue() -> c_int { - crate::safe_libc::kqueue() - } - - /// `bun.c.kevent` — raw BSD kqueue event syscall (Darwin/FreeBSD only). - #[cfg(any(target_os = "macos", target_os = "freebsd"))] - pub unsafe fn kevent( - kq: c_int, - changelist: *const libc::kevent, - nchanges: c_int, - eventlist: *mut libc::kevent, - nevents: c_int, - timeout: *const libc::timespec, - ) -> c_int { - // SAFETY: caller contract (`unsafe fn`) — all pointers forwarded verbatim. - unsafe { libc::kevent(kq, changelist, nchanges, eventlist, nevents, timeout) } - } - /// Darwin `sendfile(fd, s, off, *len, *hdtr, flags)`. /// NOTE: on `EINTR`/`EAGAIN` the kernel still writes the /// bytes-sent count back through `*len` before returning -1 — callers MUST @@ -5345,15 +5183,6 @@ pub mod c { unsafe { libc::sendfile(fd, s, off, nbytes, hdtr.cast(), sbytes, flags) } } - /// `fork(2)` — POSIX only. - #[cfg(unix)] - #[inline] - pub unsafe fn fork() -> libc::pid_t { - // SAFETY: `fork` takes no pointer arguments; the caller (`unsafe fn`) - // upholds async-signal-safety in the child. - unsafe { libc::fork() } - } - // ── Darwin libproc — process introspection (``). ── /// `struct proc_bsdinfo` (PROC_PIDTBSDINFO flavour). Fields match the SDK /// header; only `pbi_ppid` is currently consumed. @@ -5439,8 +5268,6 @@ pub mod linux { && core::mem::align_of::() == core::mem::align_of::() ); - /// Errno; aliased to `bun_errno::E`. - pub type Errno = super::E; #[inline] pub(crate) fn errno() -> c_int { super::last_errno() @@ -5740,10 +5567,6 @@ pub mod darwin { let p = unsafe { os_log_create(c"com.bun.bun".as_ptr(), c"PointsOfInterest".as_ptr()) }; core::ptr::NonNull::new(p) } - #[inline] - pub fn as_ptr(&self) -> *const OSLog { - core::ptr::from_ref(self) - } pub fn signpost(&self, name: i32) -> os_log::Signpost<'_> { os_log::Signpost { log: self, name } } @@ -7630,14 +7453,6 @@ pub fn kevent( } } -/// `clonefile` — macOS-only CoW copy. On non-Darwin returns ENOTSUP so -/// callers can fall back to `copy_file`. -#[cfg(not(target_os = "macos"))] -pub fn clonefile(from: &ZStr, to: &ZStr) -> Maybe<()> { - Err(Error::from_code_int(libc::ENOTSUP, Tag::clonefile) - .with_path_dest(from.as_bytes(), to.as_bytes())) -} - /// `clonefileat` — macOS-only CoW copy relative to directory fds. On /// non-Darwin returns ENOTSUP so callers can fall back to a manual copy. #[cfg(not(target_os = "macos"))] @@ -7822,10 +7637,6 @@ pub fn get_fd_path_w(fd: Fd, out: &mut [u16]) -> Maybe<&mut [u16]> { ) }) } -#[cfg(not(windows))] -pub fn get_fd_path_w(_fd: Fd, _out: &mut [u16]) -> Maybe<&mut [u16]> { - unreachable!("get_fd_path_w on non-Windows") -} // ── environ ── @@ -8003,33 +7814,6 @@ pub mod posix { // ── BSD sysctl(3) family ── // macOS/FreeBSD only — Linux dropped sysctl(2) and uses procfs instead. - #[cfg(any( - target_os = "macos", - target_os = "ios", - target_os = "freebsd", - target_os = "dragonfly", - target_os = "netbsd", - target_os = "openbsd" - ))] - #[inline] - // Forwards the raw out-params to libc without dereferencing them here; - // not_unsafe_ptr_arg_deref is a false positive on opaque-token forwarding. - #[allow(clippy::not_unsafe_ptr_arg_deref)] - pub fn sysctlbyname( - name: &core::ffi::CStr, - oldp: *mut c_void, - oldlenp: *mut usize, - newp: *mut c_void, - newlen: usize, - ) -> super::Maybe<()> { - // SAFETY: thin libc wrapper; pointer validity is the caller's contract. - let rc = unsafe { libc::sysctlbyname(name.as_ptr(), oldp, oldlenp, newp, newlen) }; - if rc != 0 { - return Err(super::err_with(super::Tag::TODO)); - } - Ok(()) - } - /// Typed `sysctlbyname(3)` read of a fixed-size POD value (`hw.ncpu`, /// `hw.cpufrequency`, `kern.boottime`, …). Hides the `*mut c_void` / /// `&mut len` dance. The `Zeroable` bound is the workspace's @@ -8245,20 +8029,6 @@ pub mod posix { unsafe { libc::read(fd, buf.cast(), count) } } } - #[cfg(unix)] - #[inline] - pub unsafe fn write(fd: c_int, buf: *const u8, count: usize) -> isize { - #[cfg(any(target_os = "linux", target_os = "android"))] - { - // SAFETY: caller contract — `buf` points to `count` readable bytes. - unsafe { super::linux_syscall::write_raw(fd, buf, count) } - } - #[cfg(not(any(target_os = "linux", target_os = "android")))] - { - // SAFETY: caller contract — `buf` points to `count` readable bytes. - unsafe { libc::write(fd, buf.cast(), count) } - } - } // ── poll ── /// `struct pollfd`. @@ -9079,8 +8849,7 @@ mod win_symlink_impl { #[cfg(windows)] pub use win_symlink_impl::{mkdir_w, symlink_or_junction, symlink_w, unlink_w}; -/// `link(u16, ...)` Windows arm — `CreateHardLinkW` with -/// errno mapping. The u8/ZStr overload (`link`) routes through `sys_uv::link`. +/// `link(u16, ...)` Windows arm — `CreateHardLinkW` with errno mapping. #[cfg(windows)] pub fn link_w(src: &bun_core::WStr, dest: &bun_core::WStr) -> Maybe<()> { if windows::CreateHardLinkW(dest.as_ptr(), src.as_ptr(), None) == 0 { diff --git a/src/sys/linux_syscall.rs b/src/sys/linux_syscall.rs index 40c6c95f8cf4..362c4a766d76 100644 --- a/src/sys/linux_syscall.rs +++ b/src/sys/linux_syscall.rs @@ -401,14 +401,6 @@ pub(crate) unsafe fn read_raw(fd: i32, buf: *mut u8, count: usize) -> isize { unsafe { libc::syscall(libc::SYS_read, fd, buf, count) as isize } } -/// Raw `write(2)` — libc-convention return. See `read_raw` for why this -/// bypasses rustix's typed wrapper. -#[inline] -pub(crate) unsafe fn write_raw(fd: i32, buf: *const u8, count: usize) -> isize { - // SAFETY: raw `write(2)`; kernel validates `fd`/`buf`/`count`. - unsafe { libc::syscall(libc::SYS_write, fd, buf, count) as isize } -} - /// Raw `epoll_ctl(2)` — libc-convention return. /// /// Routed via `libc::syscall(SYS_epoll_ctl, ..)` rather than rustix's typed diff --git a/src/sys/windows/mod.rs b/src/sys/windows/mod.rs index 8375d9f4ea51..13427b1c5445 100644 --- a/src/sys/windows/mod.rs +++ b/src/sys/windows/mod.rs @@ -224,17 +224,6 @@ pub(crate) fn filetime_to_timespec(filetime: i64) -> bun_libuv_sys::uv_timespec_ } } -/// Convert a [`TimeLike`](crate::TimeLike) (seconds + nanoseconds since the -/// Unix epoch) into a Windows `FILETIME`. -#[inline] -pub fn timespec_to_filetime(t: crate::TimeLike) -> FILETIME { - let ticks = (t.sec as i64 * 10_000_000 + t.nsec as i64 / 100 + EPOCH_DIFFERENCE_100NS) as u64; - FILETIME { - dwLowDateTime: ticks as u32, - dwHighDateTime: (ticks >> 32) as u32, - } -} - pub const INVALID_FILE_ATTRIBUTES: u32 = u32::MAX; pub const NT_OBJECT_PREFIX: [u16; 4] = [b'\\' as u16, b'?' as u16, b'?' as u16, b'\\' as u16]; diff --git a/src/tcc_sys/tcc.rs b/src/tcc_sys/tcc.rs index 562170f7da97..9e2d2841f141 100644 --- a/src/tcc_sys/tcc.rs +++ b/src/tcc_sys/tcc.rs @@ -61,7 +61,6 @@ tcc_externs! { fn tcc_add_library_path(s: *mut TCCState, pathname: *const c_char) -> c_int; fn tcc_add_library(s: *mut TCCState, libraryname: *const c_char) -> c_int; fn tcc_add_symbol(s: *mut TCCState, name: *const c_char, val: *const c_void) -> c_int; - fn tcc_run(s: *mut TCCState, argc: c_int, argv: *mut *mut c_char) -> c_int; fn tcc_relocate(s1: *mut TCCState) -> c_int; fn tcc_get_symbol(s: *mut TCCState, name: *const c_char) -> *mut c_void; } @@ -398,14 +397,6 @@ impl State { Ok(()) } - /// Link and run `main()` function and return its value. DO NOT call `relocate` before. - /// Returns the status code returned by the program's `main()` function. - pub fn run(&mut self, argc: c_int, argv: *const *const c_char) -> c_int { - // SAFETY: self is a valid *mut TCCState; argv points to argc NUL-terminated C strings. - // Cast const away to match the C ABI (tcc does not mutate argv). - unsafe { tcc_run(self, argc, argv as *mut *mut c_char) } - } - /// Do all relocations (needed before using `get_symbol`) /// Memory is allocated and managed internally by TinyCC. /// Returns Ok on success, error on failure. diff --git a/workspace.code-workspace b/workspace.code-workspace deleted file mode 100644 index b71214b7a770..000000000000 --- a/workspace.code-workspace +++ /dev/null @@ -1,96 +0,0 @@ -{ - "folders": [ - { - "path": "." - } -], - "settings": { - "git.autoRepositoryDetection": "openEditors", - "search.quickOpen.includeSymbols": false, - "search.seedWithNearestWord": true, - "search.smartCase": true, - "search.followSymlinks": false, - "zig.buildOnSave": false, - "files.associations": { - "*.idl": "cpp", - "memory": "cpp", - "iostream": "cpp", - "algorithm": "cpp", - "random": "cpp", - "ios": "cpp", - "filesystem": "cpp", - "__locale": "cpp", - "type_traits": "cpp", - "__mutex_base": "cpp", - "__string": "cpp", - "string": "cpp", - "string_view": "cpp", - "typeinfo": "cpp", - "__config": "cpp", - "__nullptr": "cpp", - "exception": "cpp", - "__bit_reference": "cpp", - "atomic": "cpp", - "utility": "cpp", - "sstream": "cpp", - "__functional_base": "cpp", - "new": "cpp", - "__debug": "cpp", - "__errc": "cpp", - "__hash_table": "cpp", - "__node_handle": "cpp", - "__split_buffer": "cpp", - "__threading_support": "cpp", - "__tuple": "cpp", - "array": "cpp", - "bit": "cpp", - "bitset": "cpp", - "cctype": "cpp", - "chrono": "cpp", - "clocale": "cpp", - "cmath": "cpp", - "complex": "cpp", - "condition_variable": "cpp", - "cstdarg": "cpp", - "cstddef": "cpp", - "cstdint": "cpp", - "cstdio": "cpp", - "cstdlib": "cpp", - "cstring": "cpp", - "ctime": "cpp", - "cwchar": "cpp", - "cwctype": "cpp", - "deque": "cpp", - "fstream": "cpp", - "functional": "cpp", - "initializer_list": "cpp", - "iomanip": "cpp", - "iosfwd": "cpp", - "istream": "cpp", - "iterator": "cpp", - "limits": "cpp", - "locale": "cpp", - "mutex": "cpp", - "optional": "cpp", - "ostream": "cpp", - "ratio": "cpp", - "stack": "cpp", - "stdexcept": "cpp", - "streambuf": "cpp", - "system_error": "cpp", - "thread": "cpp", - "tuple": "cpp", - "unordered_map": "cpp", - "unordered_set": "cpp", - "vector": "cpp", - "__bits": "cpp", - "__tree": "cpp", - "map": "cpp", - "numeric": "cpp", - "set": "cpp", - "__memory": "cpp", - "memory_resource": "cpp" - }, - "git.ignoreLimitWarning": true - } -}