Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

vendor(v8): add CPU trace profiler bridge

ldm06777f358075d
diff --git a/vendor/v8-152.2.0/src/cpu_profiler.rs b/vendor/v8-152.2.0/src/cpu_profiler.rs
new file mode 100644
index 000000000..3f401df09
--- /dev/null
+++ b/vendor/v8-152.2.0/src/cpu_profiler.rs
@@ -0,0 +1,155 @@
+use crate::isolate::{RealIsolate, UnsafeRawIsolatePtr};
+use std::ffi::c_void;
+use std::ptr::NonNull;
+
+type WriteCallback = unsafe extern "C" fn(*mut c_void, *const u8, usize) -> bool;
+
+unsafe extern "C" {
+ fn v8__CpuTraceProfiler__Start(
+ isolate: *mut RealIsolate,
+ sampling_interval_us: i32,
+ max_samples: u32,
+ ) -> *mut c_void;
+ fn v8__CpuTraceProfiler__Stop(
+ profiler: *mut c_void,
+ callback_context: *mut c_void,
+ callback: WriteCallback,
+ sample_count: *mut u32,
+ sample_limit_reached: *mut bool,
+ ) -> bool;
+ fn v8__CpuTraceProfiler__Cancel(profiler: *mut c_void) -> bool;
+}
+
+/// Opaque owner-thread handle for one internal V8 CPU profile.
+///
+/// The token may be transferred through a coordinator, but it must only be
+/// stopped or cancelled while its exact isolate is entered on the isolate
+/// owner thread. Dropping an unconsumed token leaks the native profiler, so
+/// embedders must preserve that lifecycle invariant through isolate teardown.
+#[derive(Debug)]
+#[must_use = "a CPU trace profiler must be stopped or cancelled on its isolate owner"]
+pub struct CpuTraceProfiler {
+ handle: NonNull<c_void>,
+}
+
+// The pointer is only an opaque transport token. Access remains restricted to
+// unsafe owner-thread methods, and no native profiler operation happens while
+// the token is in transit.
+unsafe impl Send for CpuTraceProfiler {}
+
+#[derive(Debug)]
+pub struct CpuTraceProfile {
+ pub bytes: Vec<u8>,
+ pub sample_count: u32,
+ pub sample_limit_reached: bool,
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum CpuTraceProfilerStopError {
+ InvalidOwnerOrState,
+ OutputLimitExceeded,
+}
+
+impl CpuTraceProfiler {
+ /// Starts profiling an entered, live isolate.
+ ///
+ /// # Safety
+ ///
+ /// `isolate` must identify the current isolate on its owner thread and must
+ /// remain live until the returned token is stopped or cancelled there.
+ pub unsafe fn start_on_current_isolate(
+ isolate: UnsafeRawIsolatePtr,
+ sampling_interval_us: i32,
+ max_samples: u32,
+ ) -> Option<Self> {
+ // SAFETY: UnsafeRawIsolatePtr is a transparent RealIsolate pointer. The
+ // caller owns the current-isolate and lifetime invariants documented above.
+ let isolate: *mut RealIsolate = unsafe { std::mem::transmute(isolate) };
+ let handle = unsafe {
+ v8__CpuTraceProfiler__Start(
+ isolate,
+ sampling_interval_us,
+ max_samples,
+ )
+ };
+ NonNull::new(handle).map(|handle| Self { handle })
+ }
+
+ /// Stops and serializes this profiler on its entered isolate owner.
+ ///
+ /// # Safety
+ ///
+ /// The exact isolate used by `start_on_current_isolate` must be current on
+ /// this thread. The isolate must still be live.
+ pub unsafe fn stop_on_current_isolate(
+ self,
+ max_output_bytes: usize,
+ ) -> Result<CpuTraceProfile, CpuTraceProfilerStopError> {
+ struct OutputBuffer {
+ bytes: Vec<u8>,
+ max_bytes: usize,
+ limit_exceeded: bool,
+ }
+
+ unsafe extern "C" fn append_output(
+ context: *mut c_void,
+ data: *const u8,
+ size: usize,
+ ) -> bool {
+ // SAFETY: the native serializer calls this synchronously before stop
+ // returns, with the OutputBuffer passed immediately below.
+ let output = unsafe { &mut *context.cast::<OutputBuffer>() };
+ let Some(new_len) = output.bytes.len().checked_add(size) else {
+ output.limit_exceeded = true;
+ return false;
+ };
+ if new_len > output.max_bytes || output.bytes.try_reserve(size).is_err() {
+ output.limit_exceeded = true;
+ return false;
+ }
+ // SAFETY: V8 owns a readable chunk of exactly `size` bytes for the
+ // duration of this callback.
+ let chunk = unsafe { std::slice::from_raw_parts(data, size) };
+ output.bytes.extend_from_slice(chunk);
+ true
+ }
+
+ let mut output = OutputBuffer {
+ bytes: Vec::new(),
+ max_bytes: max_output_bytes,
+ limit_exceeded: false,
+ };
+ let mut sample_count = 0;
+ let mut sample_limit_reached = false;
+ let completed = unsafe {
+ v8__CpuTraceProfiler__Stop(
+ self.handle.as_ptr(),
+ (&mut output as *mut OutputBuffer).cast(),
+ append_output,
+ &mut sample_count,
+ &mut sample_limit_reached,
+ )
+ };
+ if output.limit_exceeded {
+ return Err(CpuTraceProfilerStopError::OutputLimitExceeded);
+ }
+ if !completed {
+ return Err(CpuTraceProfilerStopError::InvalidOwnerOrState);
+ }
+ Ok(CpuTraceProfile {
+ bytes: output.bytes,
+ sample_count,
+ sample_limit_reached,
+ })
+ }
+
+ /// Cancels this profiler without serializing it.
+ ///
+ /// # Safety
+ ///
+ /// The exact live isolate used to start this profiler must be current on the
+ /// calling owner thread.
+ pub unsafe fn cancel_on_current_isolate(self) -> bool {
+ unsafe { v8__CpuTraceProfiler__Cancel(self.handle.as_ptr()) }
+ }
+}
diff --git a/vendor/v8-152.2.0/src/cpu_profiler_ext.cc b/vendor/v8-152.2.0/src/cpu_profiler_ext.cc
new file mode 100644
index 000000000..65c9f9e2b
--- /dev/null
+++ b/vendor/v8-152.2.0/src/cpu_profiler_ext.cc
@@ -0,0 +1,127 @@
+// Copyright 2026 the Moli authors. MIT license.
+
+#include "v8-profiler.h"
+#include "v8.h"
+
+#include <cstddef>
+#include <cstdint>
+
+namespace {
+
+using WriteCallback = bool (*)(void* context,
+ const char* data,
+ size_t size);
+
+struct CpuTraceProfilerState {
+ v8::Isolate* isolate;
+ v8::CpuProfiler* profiler;
+ unsigned max_samples;
+};
+
+class CallbackOutputStream final : public v8::OutputStream {
+ public:
+ CallbackOutputStream(void* context, WriteCallback callback)
+ : context_(context), callback_(callback) {}
+
+ void EndOfStream() override { ended_ = true; }
+
+ int GetChunkSize() override { return 64 * 1024; }
+
+ WriteResult WriteAsciiChunk(char* data, int size) override {
+ if (size < 0 || !callback_(context_, data, static_cast<size_t>(size))) {
+ return kAbort;
+ }
+ return kContinue;
+ }
+
+ bool ended() const { return ended_; }
+
+ private:
+ void* context_;
+ WriteCallback callback_;
+ bool ended_ = false;
+};
+
+void DisposeProfilerState(CpuTraceProfilerState* state) {
+ state->profiler->Dispose();
+ delete state;
+}
+
+} // namespace
+
+extern "C" {
+
+void* v8__CpuTraceProfiler__Start(v8::Isolate* isolate,
+ int sampling_interval_us,
+ unsigned max_samples) {
+ if (!isolate || v8::Isolate::GetCurrent() != isolate ||
+ sampling_interval_us <= 0 || max_samples == 0) {
+ return nullptr;
+ }
+
+ v8::HandleScope handle_scope(isolate);
+ auto* profiler = v8::CpuProfiler::New(
+ isolate, v8::CpuProfilingNamingMode::kDebugNaming,
+ v8::CpuProfilingLoggingMode::kLazyLogging);
+ if (!profiler) {
+ return nullptr;
+ }
+ profiler->SetSamplingInterval(sampling_interval_us);
+ const auto status = profiler->StartProfiling(
+ v8::String::Empty(isolate), v8::CpuProfilingMode::kLeafNodeLineNumbers,
+ true, max_samples);
+ if (status != v8::CpuProfilingStatus::kStarted) {
+ profiler->Dispose();
+ return nullptr;
+ }
+ return new CpuTraceProfilerState{isolate, profiler, max_samples};
+}
+
+bool v8__CpuTraceProfiler__Stop(void* raw_state,
+ void* callback_context,
+ WriteCallback callback,
+ unsigned* sample_count,
+ bool* sample_limit_reached) {
+ auto* state = static_cast<CpuTraceProfilerState*>(raw_state);
+ if (!state || !callback || !sample_count || !sample_limit_reached ||
+ v8::Isolate::GetCurrent() != state->isolate) {
+ return false;
+ }
+
+ v8::HandleScope handle_scope(state->isolate);
+ auto* profile =
+ state->profiler->StopProfiling(v8::String::Empty(state->isolate));
+ if (!profile) {
+ DisposeProfilerState(state);
+ return false;
+ }
+
+ const int recorded_samples = profile->GetSamplesCount();
+ *sample_count = recorded_samples > 0
+ ? static_cast<unsigned>(recorded_samples)
+ : 0;
+ *sample_limit_reached = *sample_count >= state->max_samples;
+
+ CallbackOutputStream stream(callback_context, callback);
+ profile->Serialize(&stream, v8::CpuProfile::SerializationFormat::kJSON);
+ profile->Delete();
+ DisposeProfilerState(state);
+ return stream.ended();
+}
+
+bool v8__CpuTraceProfiler__Cancel(void* raw_state) {
+ auto* state = static_cast<CpuTraceProfilerState*>(raw_state);
+ if (!state || v8::Isolate::GetCurrent() != state->isolate) {
+ return false;
+ }
+
+ v8::HandleScope handle_scope(state->isolate);
+ if (auto* profile =
+ state->profiler->StopProfiling(v8::String::Empty(state->isolate))) {
+ profile->Delete();
+ }
+ DisposeProfilerState(state);
+ return true;
+}
+
+} // extern "C"
diff --git a/vendor/v8-152.2.0/src/lib.rs b/vendor/v8-152.2.0/src/lib.rs
index a31423c22..95cfbbe6e 100644
--- a/vendor/v8-152.2.0/src/lib.rs
+++ b/vendor/v8-152.2.0/src/lib.rs
@@ -35,6 +35,7 @@ mod bigint;
mod binding;
mod context;
pub use context::ContextOptions;
+mod cpu_profiler;
pub mod cppgc;
mod data;
mod date;
@@ -95,6 +96,7 @@ pub mod simdutf;
pub mod V8;
pub use array_buffer::*;
+pub use cpu_profiler::{CpuTraceProfile, CpuTraceProfiler, CpuTraceProfilerStopError};
pub use data::*;
pub use exception::*;
pub use external_references::ExternalReference;