Skip to main content

script/dom/debugger/
debuggerglobalscope.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use std::cell::RefCell;
8use std::collections::HashSet;
9
10use devtools_traits::{
11    BlackboxCoverage, DebuggerValue, DevtoolScriptControlMsg, EvaluateJSReply,
12    GetEnvironmentRequest, ScriptToDevtoolsControlMsg, SourceInfo,
13};
14use dom_struct::dom_struct;
15use embedder_traits::ScriptToEmbedderChan;
16use embedder_traits::resources::{self, Resource};
17use js::context::JSContext;
18use js::rust::HandleValue;
19use js::rust::wrappers2::JS_DefineDebuggerObject;
20use net_traits::ResourceThreads;
21use profile_traits::{mem, time};
22use script_bindings::callback::{RootedCallback, TracedCallback};
23use script_bindings::cell::DomRefCell;
24use script_bindings::interfaces::HasOrigin;
25use script_bindings::reflector::DomObject;
26use servo_base::generic_channel::{GenericCallback, GenericSender, channel};
27use servo_base::id::{Index, PipelineId, PipelineNamespaceId, WorkerId};
28use servo_constellation_traits::ScriptToConstellationSender;
29use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
30use storage_traits::StorageThreads;
31
32use crate::dom::bindings::callback::ExceptionHandling;
33use crate::dom::bindings::codegen::Bindings::DebuggerGetEnvironmentEventBinding::EnvironmentInfo;
34use crate::dom::bindings::codegen::Bindings::DebuggerGlobalScopeBinding;
35use crate::dom::bindings::codegen::Bindings::DebuggerGlobalScopeBinding::GetFunctionParameterNames;
36use crate::dom::bindings::codegen::Bindings::DebuggerInterruptEventBinding::{
37    FrameInfo, FrameOffset, PauseReason,
38};
39use crate::dom::bindings::codegen::GenericBindings::DebuggerEvalEventBinding::EvalResult;
40use crate::dom::bindings::codegen::GenericBindings::DebuggerGetPossibleBreakpointsEventBinding::RecommendedBreakpointLocation;
41use crate::dom::bindings::codegen::GenericBindings::DebuggerGlobalScopeBinding::{
42    DebuggerGlobalScopeMethods, NotifyNewSource, PipelineIdInit,
43};
44use crate::dom::bindings::inheritance::Castable;
45use crate::dom::bindings::root::DomRoot;
46use crate::dom::bindings::str::DOMString;
47use crate::dom::bindings::utils::define_all_exposed_interfaces;
48use crate::dom::debugger::debuggerblackboxevent::DebuggerBlackboxEvent;
49use crate::dom::debugger::debuggerclearbreakpointevent::DebuggerClearBreakpointEvent;
50use crate::dom::debugger::debuggerframeevent::DebuggerFrameEvent;
51use crate::dom::debugger::debuggergetenvironmentevent::DebuggerGetEnvironmentEvent;
52use crate::dom::debugger::debuggerinterruptevent::DebuggerInterruptEvent;
53use crate::dom::debugger::debuggerresumeevent::DebuggerResumeEvent;
54use crate::dom::debugger::debuggersetbreakpointevent::DebuggerSetBreakpointEvent;
55use crate::dom::debugger::debuggerunblackboxevent::DebuggerUnblackboxEvent;
56use crate::dom::globalscope::GlobalScope;
57use crate::dom::types::{
58    DebuggerAddDebuggeeEvent, DebuggerEvalEvent, DebuggerGetPossibleBreakpointsEvent, Event,
59};
60#[cfg(feature = "webgpu")]
61use crate::dom::webgpu::identityhub::IdentityHub;
62use crate::event_loop::script_thread::with_script_thread;
63use crate::realms::enter_auto_realm;
64use crate::runtime::script_runtime::IntroductionType;
65
66#[dom_struct]
67/// Global scope for interacting with the devtools Debugger API.
68///
69/// <https://firefox-source-docs.mozilla.org/js/Debugger/>
70pub(crate) struct DebuggerGlobalScope {
71    global_scope: GlobalScope,
72    #[no_trace]
73    devtools_to_script_sender: GenericSender<DevtoolScriptControlMsg>,
74    #[no_trace]
75    get_possible_breakpoints_result_sender:
76        RefCell<Option<GenericSender<Vec<devtools_traits::RecommendedBreakpointLocation>>>>,
77    #[no_trace]
78    eval_result_sender: RefCell<Option<GenericSender<EvaluateJSReply>>>,
79    #[no_trace]
80    get_list_frame_result_sender: RefCell<Option<GenericSender<Vec<String>>>>,
81    #[no_trace]
82    get_environment_result_sender: RefCell<Option<GenericSender<String>>>,
83    /// Callback registered by debugger.js that returns the parameter names of a debuggee function.
84    get_function_parameter_names: DomRefCell<Option<TracedCallback<GetFunctionParameterNames>>>,
85    #[no_trace]
86    pipeline_id: PipelineId,
87    #[no_trace]
88    origin: MutableOrigin,
89}
90
91impl DebuggerGlobalScope {
92    /// Create a new heap-allocated `DebuggerGlobalScope`.
93    ///
94    /// `debugger_pipeline_id` is the pipeline id to use when creating the debugger’s [`GlobalScope`]:
95    /// - in normal script threads, it should be set to `PipelineId::new()`, because those threads can generate
96    ///   pipeline ids, and they may contain debuggees from more than one pipeline
97    /// - in web worker threads, it should be set to the pipeline id of the page that created the thread, because
98    ///   those threads can’t generate pipeline ids, and they only contain one debuggee from one pipeline
99    #[expect(unsafe_code, clippy::too_many_arguments)]
100    fn new(
101        debugger_pipeline_id: PipelineId,
102        script_to_devtools_sender: Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
103        devtools_to_script_sender: GenericSender<DevtoolScriptControlMsg>,
104        mem_profiler_chan: mem::ProfilerChan,
105        time_profiler_chan: time::ProfilerChan,
106        script_to_constellation_sender: ScriptToConstellationSender,
107        script_to_embedder_chan: ScriptToEmbedderChan,
108        resource_threads: ResourceThreads,
109        storage_threads: StorageThreads,
110        #[cfg(feature = "webgpu")] gpu_id_hub: std::sync::Arc<IdentityHub>,
111        cx: &mut JSContext,
112    ) -> DomRoot<Self> {
113        let global = Box::new(Self {
114            global_scope: GlobalScope::new_inherited(
115                script_to_devtools_sender,
116                mem_profiler_chan,
117                time_profiler_chan,
118                script_to_constellation_sender,
119                script_to_embedder_chan,
120                resource_threads,
121                storage_threads,
122                ServoUrl::parse_with_base(None, "about:internal/debugger")
123                    .expect("Guaranteed by argument"),
124                None,
125                #[cfg(feature = "webgpu")]
126                gpu_id_hub,
127                None,
128                HashSet::new(),
129                false,
130            ),
131            devtools_to_script_sender,
132            get_possible_breakpoints_result_sender: RefCell::new(None),
133            get_list_frame_result_sender: RefCell::new(None),
134            get_environment_result_sender: RefCell::new(None),
135            get_function_parameter_names: Default::default(),
136            eval_result_sender: RefCell::new(None),
137            pipeline_id: debugger_pipeline_id,
138            origin: MutableOrigin::new(ImmutableOrigin::new_opaque()),
139        });
140        let global =
141            DebuggerGlobalScopeBinding::Wrap::<crate::DomTypeHolder>(cx, &global.origin(), global);
142
143        let mut realm = enter_auto_realm(cx, &*global);
144        let mut realm = realm.current_realm();
145        define_all_exposed_interfaces(&mut realm, global.upcast());
146        assert!(unsafe {
147            // Invariants: `obj` must be a handle to a JS global object.
148            JS_DefineDebuggerObject(&mut realm, global.global_scope.reflector().get_jsobject())
149        });
150
151        global
152    }
153
154    /// Create a new heap-allocated `DebuggerGlobalScope` if the devtools_to_script_sender is not None.
155    /// Otherwise return None.
156    ///
157    /// `debugger_pipeline_id` is the pipeline id to use when creating the debugger’s [`GlobalScope`]:
158    /// - in normal script threads, it should be set to `PipelineId::new()`, because those threads can generate
159    ///   pipeline ids, and they may contain debuggees from more than one pipeline
160    /// - in web worker threads, it should be set to the pipeline id of the page that created the thread, because
161    ///   those threads can’t generate pipeline ids, and they only contain one debuggee from one pipeline
162    #[expect(clippy::too_many_arguments)]
163    pub(crate) fn new_if_needed(
164        cx: &mut JSContext,
165        debugger_pipeline_id: PipelineId,
166        script_to_devtools_sender: &Option<GenericCallback<ScriptToDevtoolsControlMsg>>,
167        devtools_to_script_sender: &Option<GenericSender<DevtoolScriptControlMsg>>,
168        mem_profiler_chan: &mem::ProfilerChan,
169        time_profiler_chan: &time::ProfilerChan,
170        script_to_constellation_sender: &ScriptToConstellationSender,
171        script_to_embedder_chan: &ScriptToEmbedderChan,
172        resource_threads: &ResourceThreads,
173        storage_threads: &StorageThreads,
174        #[cfg(feature = "webgpu")] gpu_id_hub: &std::sync::Arc<IdentityHub>,
175    ) -> Option<DomRoot<Self>> {
176        if let Some(devtools_to_script_sender) = devtools_to_script_sender {
177            let debugger_global = Self::new(
178                debugger_pipeline_id,
179                script_to_devtools_sender.clone(),
180                devtools_to_script_sender.clone(),
181                mem_profiler_chan.clone(),
182                time_profiler_chan.clone(),
183                script_to_constellation_sender.clone(),
184                script_to_embedder_chan.clone(),
185                resource_threads.clone(),
186                storage_threads.clone(),
187                #[cfg(feature = "webgpu")]
188                gpu_id_hub.clone(),
189                cx,
190            );
191            debugger_global.execute(cx);
192            Some(debugger_global)
193        } else {
194            None
195        }
196    }
197
198    pub(crate) fn origin(&self) -> MutableOrigin {
199        self.origin.clone()
200    }
201
202    pub(crate) fn as_global_scope(&self) -> &GlobalScope {
203        self.upcast::<GlobalScope>()
204    }
205
206    pub(crate) fn execute(&self, cx: &mut JSContext) {
207        let mut realm = enter_auto_realm(cx, self);
208        let cx = &mut realm.current_realm();
209
210        let bytes = resources::read_bytes(Resource::DebuggerJS);
211        let _ = self.global_scope.evaluate_js_on_global(
212            cx,
213            str::from_utf8(bytes.as_ref())
214                .expect("Should have DebuggerJS resource")
215                .into(),
216            "",
217            None,
218            None,
219        );
220    }
221
222    pub(crate) fn fire_add_debuggee(
223        &self,
224        cx: &mut JSContext,
225        debuggee_global: &GlobalScope,
226        debuggee_pipeline_id: PipelineId,
227        debuggee_worker_id: Option<WorkerId>,
228    ) {
229        let mut realm = enter_auto_realm(cx, self);
230        let cx = &mut realm;
231        let debuggee_pipeline_id =
232            crate::dom::pipelineid::PipelineId::new(cx, self.upcast(), debuggee_pipeline_id);
233        let event = DomRoot::upcast::<Event>(DebuggerAddDebuggeeEvent::new(
234            cx,
235            self.upcast(),
236            debuggee_global,
237            &debuggee_pipeline_id,
238            debuggee_worker_id.map(|id| id.to_string().into()),
239        ));
240        assert!(
241            event.fire(cx, self.upcast()),
242            "Guaranteed by DebuggerAddDebuggeeEvent::new"
243        );
244    }
245
246    #[expect(clippy::too_many_arguments)]
247    pub(crate) fn fire_eval(
248        &self,
249        cx: &mut JSContext,
250        code: DOMString,
251        debuggee_pipeline_id: PipelineId,
252        debuggee_worker_id: Option<WorkerId>,
253        frame_actor_id: Option<String>,
254        eager: bool,
255        result_sender: GenericSender<EvaluateJSReply>,
256    ) {
257        assert!(
258            self.eval_result_sender
259                .replace(Some(result_sender))
260                .is_none()
261        );
262        let mut realm = enter_auto_realm(cx, self);
263        let cx = &mut realm;
264        let debuggee_pipeline_id =
265            crate::dom::pipelineid::PipelineId::new(cx, self.upcast(), debuggee_pipeline_id);
266        let event = DomRoot::upcast::<Event>(DebuggerEvalEvent::new(
267            cx,
268            self.upcast(),
269            code,
270            &debuggee_pipeline_id,
271            debuggee_worker_id.map(|id| id.to_string().into()),
272            frame_actor_id.map(|id| id.into()),
273            eager,
274        ));
275        assert!(
276            event.fire(cx, self.upcast()),
277            "Guaranteed by DebuggerEvalEvent::new"
278        );
279    }
280
281    pub(crate) fn fire_get_possible_breakpoints(
282        &self,
283        cx: &mut JSContext,
284        spidermonkey_id: u32,
285        result_sender: GenericSender<Vec<devtools_traits::RecommendedBreakpointLocation>>,
286    ) {
287        assert!(
288            self.get_possible_breakpoints_result_sender
289                .replace(Some(result_sender))
290                .is_none()
291        );
292        let mut realm = enter_auto_realm(cx, self);
293        let cx = &mut realm.current_realm();
294        let event = DomRoot::upcast::<Event>(DebuggerGetPossibleBreakpointsEvent::new(
295            cx,
296            self.upcast(),
297            spidermonkey_id,
298        ));
299        assert!(
300            event.fire(cx, self.upcast()),
301            "Guaranteed by DebuggerGetPossibleBreakpointsEvent::new"
302        );
303    }
304
305    pub(crate) fn fire_set_breakpoint(
306        &self,
307        cx: &mut JSContext,
308        spidermonkey_id: u32,
309        script_id: u32,
310        offset: u32,
311    ) {
312        let event = DomRoot::upcast::<Event>(DebuggerSetBreakpointEvent::new(
313            cx,
314            self.upcast(),
315            spidermonkey_id,
316            script_id,
317            offset,
318        ));
319        assert!(
320            event.fire(cx, self.upcast()),
321            "Guaranteed by DebuggerSetBreakpointEvent::new"
322        );
323    }
324
325    pub(crate) fn fire_interrupt(&self, cx: &mut js::context::JSContext) {
326        let event = DomRoot::upcast::<Event>(DebuggerInterruptEvent::new(cx, self.upcast()));
327        assert!(
328            event.fire(cx, self.upcast()),
329            "Guaranteed by DebuggerInterruptEvent::new"
330        );
331    }
332
333    pub(crate) fn fire_list_frames(
334        &self,
335        cx: &mut js::context::JSContext,
336        pipeline_id: PipelineId,
337        start: u32,
338        count: u32,
339        result_sender: GenericSender<Vec<String>>,
340    ) {
341        assert!(
342            self.get_list_frame_result_sender
343                .replace(Some(result_sender))
344                .is_none()
345        );
346        let mut realm = enter_auto_realm(cx, self);
347        let cx = &mut realm.current_realm();
348        let pipeline_id = crate::dom::pipelineid::PipelineId::new(cx, self.upcast(), pipeline_id);
349        let event = DomRoot::upcast::<Event>(DebuggerFrameEvent::new(
350            cx,
351            self.upcast(),
352            &pipeline_id,
353            start,
354            count,
355        ));
356        assert!(
357            event.fire(cx, self.upcast()),
358            "Guaranteed by DebuggerFrameEvent::new"
359        );
360    }
361
362    pub(crate) fn fire_get_environment(
363        &self,
364        cx: &mut JSContext,
365        request: GetEnvironmentRequest,
366        result_sender: GenericSender<String>,
367    ) {
368        assert!(
369            self.get_environment_result_sender
370                .replace(Some(result_sender))
371                .is_none()
372        );
373        let mut realm = enter_auto_realm(cx, self);
374        let cx = &mut realm.current_realm();
375
376        let event = DomRoot::upcast::<Event>(DebuggerGetEnvironmentEvent::new(cx, self, request));
377        assert!(
378            event.fire(cx, self.upcast()),
379            "Guaranteed by DebuggerGetEnvironmentEvent::new"
380        );
381    }
382
383    pub(crate) fn fire_resume(
384        &self,
385        cx: &mut JSContext,
386        resume_limit_type: Option<String>,
387        frame_actor_id: Option<String>,
388    ) {
389        let event = DomRoot::upcast::<Event>(DebuggerResumeEvent::new(
390            cx,
391            self.upcast(),
392            resume_limit_type.map(DOMString::from),
393            frame_actor_id.map(DOMString::from),
394        ));
395        assert!(
396            event.fire(cx, self.upcast()),
397            "Guaranteed by DebuggerResumeEvent::new"
398        );
399    }
400
401    pub(crate) fn fire_clear_breakpoint(
402        &self,
403        cx: &mut JSContext,
404        spidermonkey_id: u32,
405        script_id: u32,
406        offset: u32,
407    ) {
408        let event = DomRoot::upcast::<Event>(DebuggerClearBreakpointEvent::new(
409            cx,
410            self.upcast(),
411            spidermonkey_id,
412            script_id,
413            offset,
414        ));
415        assert!(
416            event.fire(cx, self.upcast()),
417            "Guaranteed by DebuggerClearBreakpointEvent::new"
418        );
419    }
420
421    pub(crate) fn fire_blackbox(
422        &self,
423        cx: &mut JSContext,
424        spidermonkey_id: u32,
425        coverage: BlackboxCoverage,
426    ) {
427        let event = DomRoot::upcast::<Event>(DebuggerBlackboxEvent::new(
428            cx,
429            self.upcast(),
430            spidermonkey_id,
431            coverage,
432        ));
433        assert!(
434            event.fire(cx, self.upcast()),
435            "Guaranteed by DebuggerBlackboxEvent::new"
436        );
437    }
438
439    pub(crate) fn fire_unblackbox(
440        &self,
441        cx: &mut JSContext,
442        spidermonkey_id: u32,
443        coverage: BlackboxCoverage,
444    ) {
445        let event = DomRoot::upcast::<Event>(DebuggerUnblackboxEvent::new(
446            cx,
447            self.upcast(),
448            spidermonkey_id,
449            coverage,
450        ));
451        assert!(
452            event.fire(cx, self.upcast()),
453            "Guaranteed by DebuggerUnblackboxEvent::new"
454        );
455    }
456
457    pub(crate) fn pipeline_id(&self) -> PipelineId {
458        self.pipeline_id
459    }
460
461    /// Get the parameter names of a debuggee function, using the callback registered by debugger.js.
462    /// Returns `None` if no callback has been registered or the callback fails.
463    pub(crate) fn function_parameter_names(
464        &self,
465        cx: &mut JSContext,
466        function: HandleValue,
467    ) -> Option<Vec<String>> {
468        let callback = self
469            .get_function_parameter_names
470            .borrow()
471            .as_ref()
472            .map(|callback| callback.root(cx))?;
473        let names = callback
474            .Call__(cx, function, ExceptionHandling::Report)
475            .ok()?;
476        Some(names.into_iter().map(String::from).collect())
477    }
478}
479
480impl DebuggerGlobalScopeMethods<crate::DomTypeHolder> for DebuggerGlobalScope {
481    // check-tidy: no specs after this line
482    fn NotifyNewSource(&self, args: &NotifyNewSource) {
483        let Some(devtools_chan) = self.as_global_scope().devtools_chan() else {
484            return;
485        };
486        let pipeline_id = PipelineId {
487            namespace_id: PipelineNamespaceId(args.pipelineId.namespaceId),
488            index: Index::new(args.pipelineId.index).expect("`pipelineId.index` must not be zero"),
489        };
490
491        if let Some(introduction_type) = args.introductionType.as_ref() {
492            // Check the `introductionType` and `url`, decide whether or not to create a source actor, and if so,
493            // tell the devtools server to create a source actor. Based on the Firefox impl in:
494            // - getDebuggerSourceURL() <https://searchfox.org/mozilla-central/rev/85667ab51e4b2a3352f7077a9ee43513049ed2d6/devtools/server/actors/utils/source-url.js#7-42>
495            // - getSourceURL() <https://searchfox.org/mozilla-central/rev/85667ab51e4b2a3352f7077a9ee43513049ed2d6/devtools/server/actors/source.js#67-109>
496            // - resolveSourceURL() <https://searchfox.org/mozilla-central/rev/85667ab51e4b2a3352f7077a9ee43513049ed2d6/devtools/server/actors/source.js#48-66>
497            // - SourceActor#_isInlineSource <https://searchfox.org/mozilla-central/rev/85667ab51e4b2a3352f7077a9ee43513049ed2d6/devtools/server/actors/source.js#130-143>
498            // - SourceActor#url <https://searchfox.org/mozilla-central/rev/85667ab51e4b2a3352f7077a9ee43513049ed2d6/devtools/server/actors/source.js#157-162>
499
500            // Firefox impl: getDebuggerSourceURL(), getSourceURL()
501            // TODO: handle `about:srcdoc` case (see Firefox getDebuggerSourceURL())
502            // TODO: remove trailing details that may have been appended by SpiderMonkey
503            // (currently impossible to do robustly due to <https://bugzilla.mozilla.org/show_bug.cgi?id=1982001>)
504            let url_original = args.url.str();
505            // FIXME: use page/worker url as base here
506            let url_original = ServoUrl::parse(&url_original).ok();
507
508            // If the source has a `urlOverride` (aka `displayURL` aka `//# sourceURL`), it should be a valid url,
509            // possibly relative to the page/worker url, and we should treat the source as coming from that url for
510            // devtools purposes, including the file tree in the Sources tab.
511            // Firefox impl: getSourceURL()
512            let url_override = args
513                .urlOverride
514                .as_ref()
515                .map(|url| url.str())
516                // FIXME: use page/worker url as base here, not `url_original`
517                .and_then(|url| ServoUrl::parse_with_base(url_original.as_ref(), &url).ok());
518
519            // If the `introductionType` is “eval or eval-like”, the `url` won’t be meaningful, so ignore these
520            // sources unless we have a `urlOverride` (aka `displayURL` aka `//# sourceURL`).
521            // Firefox impl: getDebuggerSourceURL(), getSourceURL()
522            if [
523                IntroductionType::INJECTED_SCRIPT_STR,
524                IntroductionType::EVAL_STR,
525                IntroductionType::DEBUGGER_EVAL_STR,
526                IntroductionType::FUNCTION_STR,
527                IntroductionType::JAVASCRIPT_URL_STR,
528                IntroductionType::EVENT_HANDLER_STR,
529                IntroductionType::DOM_TIMER_STR,
530            ]
531            .contains(&&*introduction_type.str()) &&
532                url_override.is_none()
533            {
534                debug!(
535                    "Not creating debuggee: `introductionType` is `{introduction_type}` but no valid url"
536                );
537                return;
538            }
539
540            // Sources with an `introductionType` of `inlineScript` are generally inline, meaning their contents
541            // are a substring of the page markup (hence not known to SpiderMonkey, requiring plumbing in Servo).
542            // But sources with a `urlOverride` are not inline, since they get their own place in the Sources tree.
543            // nor are sources created for `<iframe srcdoc>`, since they are not necessarily a substring of the
544            // page markup as originally sent by the server.
545            // Firefox impl: SourceActor#_isInlineSource
546            // TODO: handle `about:srcdoc` case (see Firefox SourceActor#_isInlineSource)
547            let inline = introduction_type.str() == "inlineScript" && url_override.is_none();
548            let Some(url) = url_override.or(url_original) else {
549                debug!("Not creating debuggee: no valid url");
550                return;
551            };
552
553            let worker_id = args.workerId.as_ref().map(|id| id.parse().unwrap());
554
555            let source_info = SourceInfo {
556                url,
557                introduction_type: introduction_type.str().to_owned(),
558                inline,
559                worker_id,
560                content: (!inline).then(|| args.text.to_string()),
561                content_type: None, // TODO
562                spidermonkey_id: args.spidermonkeyId,
563            };
564            if let Err(error) = devtools_chan.send(ScriptToDevtoolsControlMsg::CreateSourceActor(
565                self.devtools_to_script_sender.clone(),
566                pipeline_id,
567                source_info,
568            )) {
569                warn!("Failed to send to devtools server: {error:?}");
570            }
571        } else {
572            debug!("Not creating debuggee for script with no `introductionType`");
573        }
574    }
575
576    fn GetPossibleBreakpointsResult(
577        &self,
578        event: &DebuggerGetPossibleBreakpointsEvent,
579        result: Vec<RecommendedBreakpointLocation>,
580    ) {
581        info!("GetPossibleBreakpointsResult: {event:?} {result:?}");
582        let sender = self
583            .get_possible_breakpoints_result_sender
584            .take()
585            .expect("Guaranteed by Self::fire_get_possible_breakpoints()");
586        let _ = sender.send(
587            result
588                .into_iter()
589                .map(|entry| devtools_traits::RecommendedBreakpointLocation {
590                    script_id: entry.scriptId,
591                    offset: entry.offset,
592                    line_number: entry.lineNumber,
593                    column_number: entry.columnNumber,
594                    is_step_start: entry.isStepStart,
595                })
596                .collect(),
597        );
598    }
599
600    /// Handle the result from debugger.js executeInGlobal() call.
601    ///
602    /// The result contains completion value information from the SpiderMonkey Debugger API:
603    /// <https://firefox-source-docs.mozilla.org/js/Debugger/Conventions.html#completion-values>
604    fn EvalResult(&self, _event: &DebuggerEvalEvent, result: &EvalResult) {
605        let sender = self
606            .eval_result_sender
607            .take()
608            .expect("Guaranteed by Self::fire_eval()");
609
610        let has_exception = result.hasException.unwrap_or(false);
611        let value = match serde_json::from_str::<devtools_traits::DebuggerValue>(
612            &result.serializedValue.str(),
613        ) {
614            Ok(value) => value,
615            Err(error) => {
616                warn!("Failed to parse serialized debugger eval value: {error}");
617                devtools_traits::DebuggerValue::StringValue(
618                    "failed to parse eval result".to_string(),
619                )
620            },
621        };
622
623        let exception_message = result
624            .exceptionMessage
625            .as_ref()
626            .map(|message| message.str().to_string());
627
628        let reply = EvaluateJSReply {
629            value,
630            exception_message,
631            has_exception,
632        };
633
634        let _ = sender.send(reply);
635    }
636
637    fn RegisterObjectActor(&self, serialized_value: DOMString) -> Option<DOMString> {
638        let chan = self.upcast::<GlobalScope>().devtools_chan()?;
639        let (tx, rx) = channel::<String>().unwrap();
640
641        let value =
642            match serde_json::from_str::<devtools_traits::DebuggerValue>(&serialized_value.str()) {
643                Ok(value) => value,
644                Err(error) => {
645                    warn!("Failed to parse serialized debugger object value: {error}");
646                    return None;
647                },
648            };
649
650        let msg = ScriptToDevtoolsControlMsg::CreateObjectActor(tx, value);
651        let _ = chan.send(msg);
652
653        rx.recv().ok().map(DOMString::from)
654    }
655
656    fn PauseAndRespond(
657        &self,
658        pipeline_id: &PipelineIdInit,
659        frame_offset: &FrameOffset,
660        pause_reason: &PauseReason,
661    ) {
662        let pipeline_id = PipelineId {
663            namespace_id: PipelineNamespaceId(pipeline_id.namespaceId),
664            index: Index::new(pipeline_id.index).expect("`pipelineId.index` must not be zero"),
665        };
666
667        let frame_offset = devtools_traits::FrameOffset {
668            actor: frame_offset.frameActorId.clone().into(),
669            column: frame_offset.column,
670            line: frame_offset.line,
671        };
672
673        let pause_reason = devtools_traits::PauseReason {
674            type_: pause_reason.type_.clone().into(),
675            on_next: pause_reason.onNext,
676        };
677
678        if let Some(chan) = self.upcast::<GlobalScope>().devtools_chan() {
679            let msg =
680                ScriptToDevtoolsControlMsg::DebuggerPause(pipeline_id, frame_offset, pause_reason);
681            let _ = chan.send(msg);
682        }
683
684        with_script_thread(|script_thread| {
685            script_thread.enter_debugger_pause_loop();
686        });
687    }
688
689    fn RegisterFrameActor(
690        &self,
691        pipeline_id: &PipelineIdInit,
692        result: &FrameInfo,
693    ) -> Option<DOMString> {
694        let pipeline_id = PipelineId {
695            namespace_id: PipelineNamespaceId(pipeline_id.namespaceId),
696            index: Index::new(pipeline_id.index).expect("`pipelineId.index` must not be zero"),
697        };
698
699        let chan = self.upcast::<GlobalScope>().devtools_chan()?;
700        let (tx, rx) = channel::<String>().unwrap();
701
702        let this_value = match serde_json::from_str::<devtools_traits::DebuggerValue>(
703            &result.serializedThis.str(),
704        ) {
705            Ok(this_value) => this_value,
706            Err(error) => {
707                warn!("Failed to parse serialized debugger frame this value: {error}");
708                return None;
709            },
710        };
711
712        let frame = devtools_traits::FrameInfo {
713            display_name: result.displayName.clone().map(String::from),
714            on_stack: result.onStack,
715            oldest: result.oldest,
716            this_value,
717            terminated: result.terminated,
718            type_: result.type_.clone().into(),
719            url: result.url.clone().into(),
720        };
721        let msg = ScriptToDevtoolsControlMsg::CreateFrameActor(tx, pipeline_id, frame);
722        let _ = chan.send(msg);
723
724        rx.recv().ok().map(DOMString::from)
725    }
726
727    fn ListFramesResult(&self, frame_actor_ids: Vec<DOMString>) {
728        info!("ListFramesResult: {frame_actor_ids:?}");
729        let sender = self
730            .get_list_frame_result_sender
731            .take()
732            .expect("Guaranteed by Self::fire_list_frames()");
733
734        let _ = sender.send(frame_actor_ids.into_iter().map(|i| i.into()).collect());
735    }
736
737    fn RegisterEnvironmentActor(
738        &self,
739        environment: &EnvironmentInfo,
740        parent: Option<DOMString>,
741        actor: Option<DOMString>,
742    ) -> Option<DOMString> {
743        let chan = self.upcast::<GlobalScope>().devtools_chan()?;
744        let (tx, rx) = channel::<String>().unwrap();
745
746        let binding_variables = match serde_json::from_str::<Vec<devtools_traits::PropertyDescriptor>>(
747            &environment.serializedBindings.str(),
748        ) {
749            Ok(binding_variables) => binding_variables,
750            Err(error) => {
751                warn!("Failed to parse serialized debugger environment bindings: {error}");
752                return None;
753            },
754        };
755        let object = match environment.serializedObject.as_ref() {
756            Some(serialized_object) => {
757                match serde_json::from_str::<DebuggerValue>(&serialized_object.str()) {
758                    Ok(object) => Some(object),
759                    Err(error) => {
760                        warn!("Failed to parse serialized debugger environment object: {error}");
761                        return None;
762                    },
763                }
764            },
765            None => None,
766        };
767        let environment = devtools_traits::EnvironmentInfo {
768            type_: environment.type_.clone().map(String::from),
769            scope_kind: environment.scopeKind.clone().map(String::from),
770            function_display_name: environment.functionDisplayName.clone().map(String::from),
771            object,
772            binding_variables,
773        };
774
775        let msg = ScriptToDevtoolsControlMsg::CreateEnvironmentActor(
776            tx,
777            environment,
778            parent.map(String::from),
779            actor.map(String::from),
780        );
781        let _ = chan.send(msg);
782
783        rx.recv().ok().map(DOMString::from)
784    }
785
786    fn SetGetFunctionParameterNamesCallback(
787        &self,
788        callback: RootedCallback<GetFunctionParameterNames>,
789    ) {
790        *self.get_function_parameter_names.borrow_mut() = Some(callback.to_traced());
791    }
792
793    fn GetEnvironmentResult(&self, environment_actor_id: DOMString) {
794        let sender = self
795            .get_environment_result_sender
796            .take()
797            .expect("Guaranteed by Self::fire_get_environment()");
798
799        let _ = sender.send(environment_actor_id.into());
800    }
801}
802
803impl HasOrigin for DebuggerGlobalScope {
804    fn origin(&self) -> MutableOrigin {
805        DebuggerGlobalScope::origin(self)
806    }
807}