provekit_noir_debugger 1.0.0-beta.11-alpha.6

Debugger for Noir
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
use std::collections::BTreeMap;
use std::io::{Read, Write};

use acvm::{BlackBoxFunctionSolver, FieldElement};
use bn254_blackbox_solver::Bn254BlackBoxSolver;
use nargo::NargoError;

use crate::DebugProject;
use crate::context::{DebugCommandResult, DebugLocation, RunParams};
use crate::context::{DebugContext, DebugExecutionResult};
use crate::foreign_calls::DefaultDebugForeignCallExecutor;

use dap::errors::ServerError;
use dap::events::StoppedEventBody;
use dap::prelude::Event;
use dap::requests::{Command, Request, SetBreakpointsArguments};
use dap::responses::{
    ContinueResponse, DisassembleResponse, ResponseBody, ScopesResponse, SetBreakpointsResponse,
    SetExceptionBreakpointsResponse, SetInstructionBreakpointsResponse, StackTraceResponse,
    ThreadsResponse, VariablesResponse,
};
use dap::server::Server;
use dap::types::{
    Breakpoint, DisassembledInstruction, Scope, Source, StackFrame, SteppingGranularity,
    StoppedEventReason, Thread, Variable,
};
use noirc_artifacts::debug::DebugArtifact;

use fm::FileId;

type BreakpointId = i64;

pub struct DapSession<'a, R: Read, W: Write, B: BlackBoxFunctionSolver<FieldElement>> {
    server: &'a mut Server<R, W>,
    context: DebugContext<'a, B>,
    debug_artifact: &'a DebugArtifact,
    running: bool,
    next_breakpoint_id: BreakpointId,
    instruction_breakpoints: Vec<(DebugLocation, BreakpointId)>,
    source_breakpoints: BTreeMap<FileId, Vec<(DebugLocation, BreakpointId)>>,
    last_result: DebugCommandResult,
}

enum ScopeReferences {
    Locals = 1,
    WitnessMap = 2,
    InvalidScope = 0,
}

impl From<i64> for ScopeReferences {
    fn from(value: i64) -> Self {
        match value {
            1 => Self::Locals,
            2 => Self::WitnessMap,
            _ => Self::InvalidScope,
        }
    }
}

impl<'a, R: Read, W: Write, B: BlackBoxFunctionSolver<FieldElement>> DapSession<'a, R, W, B> {
    pub fn new(
        server: &'a mut Server<R, W>,
        solver: &'a B,
        project: &'a DebugProject,
        debug_artifact: &'a DebugArtifact,
        foreign_call_resolver_url: Option<String>,
    ) -> Self {
        let context = DebugContext::new(
            solver,
            &project.compiled_program.program.functions,
            debug_artifact,
            project.initial_witness.clone(),
            Box::new(DefaultDebugForeignCallExecutor::from_artifact(
                std::io::stdout(),
                foreign_call_resolver_url,
                debug_artifact,
                Some(project.root_dir.clone()),
                project.package_name.clone(),
            )),
            &project.compiled_program.program.unconstrained_functions,
        );
        Self {
            server,
            context,
            debug_artifact,
            running: false,
            next_breakpoint_id: 1,
            instruction_breakpoints: vec![],
            source_breakpoints: BTreeMap::new(),
            last_result: DebugCommandResult::Ok,
        }
    }

    fn send_stopped_event(&mut self, reason: StoppedEventReason) -> Result<(), ServerError> {
        let description = format!("{:?}", &reason);
        self.server.send_event(Event::Stopped(StoppedEventBody {
            reason,
            description: Some(description),
            thread_id: Some(0),
            preserve_focus_hint: Some(false),
            text: None,
            all_threads_stopped: Some(false),
            hit_breakpoint_ids: None,
        }))?;
        Ok(())
    }

    pub fn run_loop(&mut self) -> Result<(), ServerError> {
        self.running = self.context.get_current_debug_location().is_some();

        if self.running && self.context.get_current_source_location().is_none() {
            // TODO: remove this? This is to ensure that the tool has a proper
            // source location to show when first starting the debugger, but
            // maybe the default behavior should be to start executing until the
            // first breakpoint set.
            _ = self.context.next_into();
        }

        self.server.send_event(Event::Initialized)?;
        self.send_stopped_event(StoppedEventReason::Entry)?;

        while self.running {
            let req = match self.server.poll_request()? {
                Some(req) => req,
                None => break,
            };
            match req.command {
                Command::Disconnect(_) => {
                    eprintln!("INFO: ending debugging session");
                    self.running = false;
                    break;
                }
                Command::SetBreakpoints(_) => {
                    self.handle_set_source_breakpoints(req)?;
                }
                Command::SetExceptionBreakpoints(_) => {
                    self.server.respond(req.success(ResponseBody::SetExceptionBreakpoints(
                        SetExceptionBreakpointsResponse { breakpoints: None },
                    )))?;
                }
                Command::SetInstructionBreakpoints(_) => {
                    self.handle_set_instruction_breakpoints(req)?;
                }
                Command::Threads => {
                    self.server.respond(req.success(ResponseBody::Threads(ThreadsResponse {
                        threads: vec![Thread { id: 0, name: "main".to_string() }],
                    })))?;
                }
                Command::StackTrace(_) => {
                    self.handle_stack_trace(req)?;
                }
                Command::Disassemble(_) => {
                    self.handle_disassemble(req)?;
                }
                Command::StepIn(ref args) => {
                    let granularity =
                        args.granularity.as_ref().unwrap_or(&SteppingGranularity::Statement);
                    match granularity {
                        SteppingGranularity::Instruction => self.handle_step(req)?,
                        _ => self.handle_next_into(req)?,
                    }
                }
                Command::StepOut(ref args) => {
                    let granularity =
                        args.granularity.as_ref().unwrap_or(&SteppingGranularity::Statement);
                    match granularity {
                        SteppingGranularity::Instruction => self.handle_step(req)?,
                        _ => self.handle_next_out(req)?,
                    }
                }
                Command::Next(ref args) => {
                    let granularity =
                        args.granularity.as_ref().unwrap_or(&SteppingGranularity::Statement);
                    match granularity {
                        SteppingGranularity::Instruction => self.handle_step(req)?,
                        _ => self.handle_next_over(req)?,
                    }
                }
                Command::Continue(_) => {
                    self.handle_continue(req)?;
                }
                Command::Scopes(_) => {
                    self.handle_scopes(req)?;
                }
                Command::Variables(ref _args) => {
                    self.handle_variables(req)?;
                }
                _ => {
                    eprintln!("ERROR: unhandled command: {:?}", req.command);
                }
            }
        }
        Ok(())
    }

    fn build_stack_trace(&self) -> Vec<StackFrame> {
        let stack_frames = self.context.get_variables();

        self.context
            .get_source_call_stack()
            .iter()
            .enumerate()
            .map(|(index, (debug_location, source_location))| {
                let line_number =
                    self.debug_artifact.location_line_number(*source_location).unwrap();
                let column_number =
                    self.debug_artifact.location_column_number(*source_location).unwrap();

                let name = match stack_frames.get(index) {
                    Some(frame) => format!("{} {}", frame.function_name, index),
                    None => format!("frame #{index}"),
                };
                let address = self.context.debug_location_to_address(debug_location);

                StackFrame {
                    id: index as i64,
                    name,
                    source: Some(Source {
                        path: self.debug_artifact.file_map[&source_location.file]
                            .path
                            .to_str()
                            .map(String::from),
                        ..Source::default()
                    }),
                    line: line_number as i64,
                    column: column_number as i64,
                    instruction_pointer_reference: Some(address.to_string()),
                    ..StackFrame::default()
                }
            })
            .rev()
            .collect()
    }

    fn handle_stack_trace(&mut self, req: Request) -> Result<(), ServerError> {
        let frames = self.build_stack_trace();
        let total_frames = Some(frames.len() as i64);
        self.server.respond(req.success(ResponseBody::StackTrace(StackTraceResponse {
            stack_frames: frames,
            total_frames,
        })))?;
        Ok(())
    }

    fn handle_disassemble(&mut self, req: Request) -> Result<(), ServerError> {
        let Command::Disassemble(ref args) = req.command else {
            unreachable!("handle_disassemble called on a non disassemble request");
        };

        // we assume memory references are unsigned integers
        let starting_address = args.memory_reference.parse::<i64>().unwrap_or(0);
        let instruction_offset = args.instruction_offset.unwrap_or(0);

        let mut address = starting_address + instruction_offset;
        let mut count = args.instruction_count;

        let mut instructions: Vec<DisassembledInstruction> = vec![];

        while count > 0 {
            let debug_location = if address >= 0 {
                self.context.address_to_debug_location(address as usize)
            } else {
                None
            };

            if let Some(debug_location) = debug_location {
                instructions.push(DisassembledInstruction {
                    address: address.to_string(),
                    // we'll use the instruction_bytes field to render the OpcodeLocation
                    instruction_bytes: Some(debug_location.to_string()),
                    instruction: self.context.render_opcode_at_location(&debug_location),
                    ..DisassembledInstruction::default()
                });
            } else {
                // entry for invalid location to fill up the request
                instructions.push(DisassembledInstruction {
                    address: "---".to_owned(),
                    instruction: "---".to_owned(),
                    ..DisassembledInstruction::default()
                });
            }
            count -= 1;
            address += 1;
        }

        self.server.respond(
            req.success(ResponseBody::Disassemble(DisassembleResponse { instructions })),
        )?;
        Ok(())
    }

    fn handle_step(&mut self, req: Request) -> Result<(), ServerError> {
        let result = self.context.step_into_opcode();
        eprintln!("INFO: stepped by instruction with result {result:?}");
        self.server.respond(req.ack()?)?;
        self.handle_execution_result(result)
    }

    fn handle_next_into(&mut self, req: Request) -> Result<(), ServerError> {
        let result = self.context.next_into();
        eprintln!("INFO: stepped into by statement with result {result:?}");
        self.server.respond(req.ack()?)?;
        self.handle_execution_result(result)
    }

    fn handle_next_out(&mut self, req: Request) -> Result<(), ServerError> {
        let result = self.context.next_out();
        eprintln!("INFO: stepped out by statement with result {result:?}");
        self.server.respond(req.ack()?)?;
        self.handle_execution_result(result)
    }

    fn handle_next_over(&mut self, req: Request) -> Result<(), ServerError> {
        let result = self.context.next_over();
        eprintln!("INFO: stepped over by statement with result {result:?}");
        self.server.respond(req.ack()?)?;
        self.handle_execution_result(result)
    }

    fn handle_continue(&mut self, req: Request) -> Result<(), ServerError> {
        let result = self.context.cont();
        eprintln!("INFO: continue with result {result:?}");
        self.server.respond(req.success(ResponseBody::Continue(ContinueResponse {
            all_threads_continued: Some(true),
        })))?;
        self.handle_execution_result(result)
    }

    fn find_breakpoints_at_location(&self, debug_location: &DebugLocation) -> Vec<i64> {
        let mut result = vec![];
        for (location, id) in &self.instruction_breakpoints {
            if debug_location == location {
                result.push(*id);
            }
        }
        for breakpoints in self.source_breakpoints.values() {
            for (location, id) in breakpoints {
                if debug_location == location {
                    result.push(*id);
                }
            }
        }
        result
    }

    fn handle_execution_result(&mut self, result: DebugCommandResult) -> Result<(), ServerError> {
        self.last_result = result;
        match &self.last_result {
            DebugCommandResult::Done => {
                self.running = false;
            }
            DebugCommandResult::Ok => {
                self.server.send_event(Event::Stopped(StoppedEventBody {
                    reason: StoppedEventReason::Pause,
                    description: None,
                    thread_id: Some(0),
                    preserve_focus_hint: Some(false),
                    text: None,
                    all_threads_stopped: Some(false),
                    hit_breakpoint_ids: None,
                }))?;
            }
            DebugCommandResult::BreakpointReached(location) => {
                let breakpoint_ids = self.find_breakpoints_at_location(location);
                self.server.send_event(Event::Stopped(StoppedEventBody {
                    reason: StoppedEventReason::Breakpoint,
                    description: Some(String::from("Paused at breakpoint")),
                    thread_id: Some(0),
                    preserve_focus_hint: Some(false),
                    text: None,
                    all_threads_stopped: Some(false),
                    hit_breakpoint_ids: Some(breakpoint_ids),
                }))?;
            }
            DebugCommandResult::Error(_) => self.server.send_event(Event::Terminated(None))?,
        }
        Ok(())
    }

    fn get_next_breakpoint_id(&mut self) -> BreakpointId {
        let id = self.next_breakpoint_id;
        self.next_breakpoint_id += 1;
        id
    }

    fn reinstall_breakpoints(&mut self) {
        self.context.clear_breakpoints();
        for (location, _) in &self.instruction_breakpoints {
            self.context.add_breakpoint(*location);
        }
        for breakpoints in self.source_breakpoints.values() {
            for (location, _) in breakpoints {
                self.context.add_breakpoint(*location);
            }
        }
    }

    fn handle_set_instruction_breakpoints(&mut self, req: Request) -> Result<(), ServerError> {
        let Command::SetInstructionBreakpoints(ref args) = req.command else {
            unreachable!("handle_set_instruction_breakpoints called on a different request");
        };

        // compute breakpoints to set and return
        let mut breakpoints_to_set: Vec<(DebugLocation, i64)> = vec![];
        let breakpoints: Vec<Breakpoint> = args
            .breakpoints
            .iter()
            .map(|breakpoint| {
                let offset = breakpoint.offset.unwrap_or(0);
                let address = breakpoint.instruction_reference.parse::<i64>().unwrap_or(0) + offset;
                let Ok(address): Result<usize, _> = address.try_into() else {
                    return Breakpoint {
                        verified: false,
                        message: Some(String::from("Invalid instruction reference/offset")),
                        ..Breakpoint::default()
                    };
                };
                let Some(location) = self
                    .context
                    .address_to_debug_location(address)
                    .filter(|location| self.context.is_valid_debug_location(location))
                else {
                    return Breakpoint {
                        verified: false,
                        message: Some(String::from("Invalid opcode location")),
                        ..Breakpoint::default()
                    };
                };
                let id = self.get_next_breakpoint_id();
                breakpoints_to_set.push((location, id));
                Breakpoint {
                    id: Some(id),
                    verified: true,
                    offset: Some(0),
                    instruction_reference: Some(address.to_string()),
                    ..Breakpoint::default()
                }
            })
            .collect();

        // actually set the computed breakpoints
        self.instruction_breakpoints = breakpoints_to_set;
        self.reinstall_breakpoints();

        // response to request
        self.server.respond(req.success(ResponseBody::SetInstructionBreakpoints(
            SetInstructionBreakpointsResponse { breakpoints },
        )))?;
        Ok(())
    }

    fn find_file_id(&self, source_path: &str) -> Option<FileId> {
        let file_map = &self.debug_artifact.file_map;
        let found = file_map.iter().find(|(_, debug_file)| match debug_file.path.to_str() {
            Some(debug_file_path) => debug_file_path == source_path,
            None => false,
        });
        found.map(|iter| *iter.0)
    }

    fn map_source_breakpoints(&mut self, args: &SetBreakpointsArguments) -> Vec<Breakpoint> {
        let Some(source) = &args.source.path else {
            return vec![];
        };
        let Some(file_id) = self.find_file_id(source) else {
            eprintln!("WARN: file ID for source {source} not found");
            return vec![];
        };
        let Some(breakpoints) = &args.breakpoints else {
            return vec![];
        };
        let mut breakpoints_to_set: Vec<(DebugLocation, i64)> = vec![];
        let breakpoints = breakpoints
            .iter()
            .map(|breakpoint| {
                let line = breakpoint.line;
                let Some(location) = self.context.find_opcode_for_source_location(&file_id, line)
                else {
                    return Breakpoint {
                        verified: false,
                        message: Some(String::from(
                            "Source location cannot be matched to opcode location",
                        )),
                        ..Breakpoint::default()
                    };
                };
                // TODO: line will not necessarily be the one requested; we
                // should do the reverse mapping and retrieve the actual source
                // code line number
                if !self.context.is_valid_debug_location(&location) {
                    return Breakpoint {
                        verified: false,
                        message: Some(String::from("Invalid opcode location")),
                        ..Breakpoint::default()
                    };
                }
                let breakpoint_address = self.context.debug_location_to_address(&location);
                let instruction_reference = format!("{breakpoint_address}");
                let breakpoint_id = self.get_next_breakpoint_id();
                breakpoints_to_set.push((location, breakpoint_id));
                Breakpoint {
                    id: Some(breakpoint_id),
                    verified: true,
                    source: Some(args.source.clone()),
                    line: Some(line),
                    instruction_reference: Some(instruction_reference),
                    offset: Some(0),
                    ..Breakpoint::default()
                }
            })
            .collect();

        self.source_breakpoints.insert(file_id, breakpoints_to_set);

        breakpoints
    }

    fn handle_set_source_breakpoints(&mut self, req: Request) -> Result<(), ServerError> {
        let Command::SetBreakpoints(ref args) = req.command else {
            unreachable!("handle_set_source_breakpoints called on a different request");
        };
        let breakpoints = self.map_source_breakpoints(args);
        self.reinstall_breakpoints();
        self.server.respond(
            req.success(ResponseBody::SetBreakpoints(SetBreakpointsResponse { breakpoints })),
        )?;
        Ok(())
    }

    fn handle_scopes(&mut self, req: Request) -> Result<(), ServerError> {
        self.server.respond(req.success(ResponseBody::Scopes(ScopesResponse {
            scopes: vec![
                Scope {
                    name: String::from("Locals"),
                    variables_reference: ScopeReferences::Locals as i64,
                    ..Scope::default()
                },
                Scope {
                    name: String::from("Witness Map"),
                    variables_reference: ScopeReferences::WitnessMap as i64,
                    ..Scope::default()
                },
            ],
        })))?;
        Ok(())
    }

    fn build_local_variables(&self) -> Vec<Variable> {
        let Some(current_stack_frame) = self.context.current_stack_frame() else {
            return vec![];
        };

        let mut variables = current_stack_frame
            .variables
            .iter()
            .map(|(name, value, _var_type)| Variable {
                name: String::from(*name),
                value: format!("{:?}", *value),
                ..Variable::default()
            })
            .collect::<Vec<Variable>>();

        variables.sort_by(|a, b| a.name.partial_cmp(&b.name).unwrap());
        variables
    }

    fn build_witness_map(&self) -> Vec<Variable> {
        self.context
            .get_witness_map()
            .clone()
            .into_iter()
            .map(|(witness, value)| Variable {
                name: format!("_{}", witness.witness_index()),
                value: format!("{value:?}"),
                ..Variable::default()
            })
            .collect()
    }

    fn handle_variables(&mut self, req: Request) -> Result<(), ServerError> {
        let Command::Variables(ref args) = req.command else {
            unreachable!("handle_variables called on a different request");
        };
        let scope: ScopeReferences = args.variables_reference.into();
        let variables: Vec<_> = match scope {
            ScopeReferences::Locals => self.build_local_variables(),
            ScopeReferences::WitnessMap => self.build_witness_map(),
            _ => {
                eprintln!(
                    "handle_variables with an unknown variables_reference {}",
                    args.variables_reference
                );
                vec![]
            }
        };
        self.server
            .respond(req.success(ResponseBody::Variables(VariablesResponse { variables })))?;
        Ok(())
    }

    pub fn last_error(self) -> Option<NargoError<FieldElement>> {
        match self.last_result {
            DebugCommandResult::Error(error) => Some(error),
            _ => None,
        }
    }
}

pub fn run_session<R: Read, W: Write>(
    server: &mut Server<R, W>,
    project: DebugProject,
    run_params: RunParams,
) -> Result<DebugExecutionResult, ServerError> {
    let debug_artifact = DebugArtifact {
        debug_symbols: project.compiled_program.debug.clone(),
        file_map: project.compiled_program.file_map.clone(),
    };

    let solver = Bn254BlackBoxSolver(run_params.pedantic_solving);
    let mut session =
        DapSession::new(server, &solver, &project, &debug_artifact, run_params.oracle_resolver_url);

    session.run_loop()?;
    if session.context.is_solved() {
        let solved_witness_stack = session.context.finalize();
        Ok(DebugExecutionResult::Solved(solved_witness_stack))
    } else {
        match session.last_error() {
            // Expose the last known error
            Some(error) => Ok(DebugExecutionResult::Error(error)),
            None => Ok(DebugExecutionResult::Incomplete),
        }
    }
}