quickjs_jit_stdlib/llrt/llrt_hooking/
lib.rs1use std::env;
6
7use crate::utils::{object::ObjectExt, provider::ProviderType};
8use once_cell::sync::Lazy;
9use rquickjs::{Ctx, Exception, Function, Result, Value};
10
11pub static HOOKING_MODE: Lazy<bool> =
12 Lazy::new(|| env::var("LLRT_ASYNC_HOOKS").as_deref() == Ok("1"));
13
14#[derive(PartialEq)]
15pub enum HookType {
16 Init,
17 Before,
18 After,
19}
20
21pub fn invoke_async_hook(
22 ctx: &Ctx<'_>,
23 hook_type: HookType,
24 provider_type: ProviderType,
25 uid: usize,
26) -> Result<()> {
27 if !HOOKING_MODE.to_owned() {
28 return Ok(());
29 }
30
31 let hook_ = match hook_type {
32 HookType::Init => "init",
33 HookType::Before => "before",
34 HookType::After => "after",
35 };
36
37 let provider_ = match provider_type {
38 ProviderType::None if hook_type != HookType::Init => "",
39 ProviderType::None => {
40 return Err(Exception::throw_type(
41 ctx,
42 "Asynchronous types cannot be omitted in init hooks.",
43 ))
44 }
45 ProviderType::Resource(s) => &["Resource(", &s, ")"].concat(),
46 ProviderType::Immediate => "Immediate",
48 ProviderType::Interval => "Interval",
49 ProviderType::MessagePort => "MessagePort",
50 ProviderType::Microtask => "Microtask",
51 ProviderType::TickObject => "TickObject",
52 ProviderType::Timeout => "Timeout",
53 ProviderType::FsReqCallback => "FSREQCALLBACK",
55 ProviderType::GetAddrInfoReqWrap => "GETADDRINFOREQWRAP",
56 ProviderType::GetNameInfoReqWrap => "GETNAMEINFOREQWRAP",
57 ProviderType::PipeWrap => "PIPEWRAP",
58 ProviderType::StatWatcher => "STATWACHER",
59 ProviderType::TcpWrap => "TCPWRAP",
60 ProviderType::TimerWrap => "TIMERWRAP",
61 ProviderType::TlsWrap => "TLSWRAP",
62 ProviderType::UdpWrap => "UDPWRAP",
63 };
64
65 let invoke_async_hook = ctx
66 .globals()
67 .get_optional::<_, Function>("invokeAsyncHook")?;
68 if let Some(func) = &invoke_async_hook {
69 func.call::<_, ()>((hook_, provider_, uid))?;
70 }
71 Ok(())
72}
73
74pub fn register_finalization_registry<'js>(
75 ctx: &Ctx<'js>,
76 target: Value<'js>,
77 uid: usize,
78) -> Result<()> {
79 if !HOOKING_MODE.to_owned() {
80 return Ok(());
81 }
82
83 if let Ok(register) =
84 ctx.eval::<Function<'js>, &str>("globalThis.asyncFinalizationRegistry.register")
85 {
86 let _ = register.call::<_, ()>((target, uid));
87 }
88 Ok(())
89}