-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathdwarf_bridge.rs
More file actions
2570 lines (2442 loc) · 115 KB
/
dwarf_bridge.rs
File metadata and controls
2570 lines (2442 loc) · 115 KB
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! DWARF debugging information bridge
//!
//! This module handles integration with DWARF debug information for
//! variable type resolution and evaluation result processing.
use super::context::{CodeGenError, EbpfContext, Result};
use ghostscope_dwarf::{
ComputeStep, DirectValueResult, EvaluationResult, LocationResult, MemoryAccessSize, TypeInfo,
VariableWithEvaluation,
};
use ghostscope_process::module_probe;
use inkwell::values::{BasicValueEnum, IntValue, PointerValue};
use tracing::{debug, warn};
impl<'ctx, 'dw> EbpfContext<'ctx, 'dw> {
/// Compute a stable cookie for a module when per-PID offsets are unavailable (via coordinator).
fn fallback_cookie_from_module_path(&self, module_path: &str) -> u64 {
module_probe::cookie_for_path(module_path)
}
/// Compute section code for an address within a module (text=0, rodata=1, data=2, bss=3).
fn section_code_for_address(&mut self, module_path: &str, link_addr: u64) -> u8 {
if let Some(analyzer) = self.process_analyzer.as_deref_mut() {
if let Some(st) = analyzer.classify_section_for_address(module_path, link_addr) {
return match st {
ghostscope_dwarf::core::SectionType::Text => 0,
ghostscope_dwarf::core::SectionType::Rodata => 1,
ghostscope_dwarf::core::SectionType::Data => 2,
ghostscope_dwarf::core::SectionType::Bss => 3,
_ => 2,
};
}
}
2
}
/// Compute cookie for module using coordinator policy.
fn cookie_for_module_or_fallback(&mut self, module_path: &str) -> u64 {
self.fallback_cookie_from_module_path(module_path)
}
/// Helper: unwrap typedef/qualified wrappers to the underlying type
fn unwrap_type_aliases(mut t: &TypeInfo) -> &TypeInfo {
loop {
match t {
TypeInfo::TypedefType {
underlying_type, ..
} => t = underlying_type.as_ref(),
TypeInfo::QualifiedType {
underlying_type, ..
} => t = underlying_type.as_ref(),
_ => break,
}
}
t
}
/// Helper: determine if a DWARF type represents an aggregate (struct/union/array)
fn is_aggregate_type(&self, t: &TypeInfo) -> bool {
matches!(
Self::unwrap_type_aliases(t),
TypeInfo::StructType { .. } | TypeInfo::UnionType { .. } | TypeInfo::ArrayType { .. }
)
}
/// Convert EvaluationResult to LLVM value
pub fn evaluate_result_to_llvm_value(
&mut self,
evaluation_result: &EvaluationResult,
dwarf_type: &TypeInfo,
var_name: &str,
pc_address: u64,
status_ptr: Option<PointerValue<'ctx>>,
) -> Result<BasicValueEnum<'ctx>> {
debug!(
"Converting EvaluationResult to LLVM value for variable: {}",
var_name
);
debug!("Evaluation context PC address: 0x{:x}", pc_address);
// Get pt_regs parameter
let pt_regs_ptr = self.get_pt_regs_parameter()?;
match evaluation_result {
EvaluationResult::DirectValue(direct) => {
self.generate_direct_value(direct, pt_regs_ptr)
}
EvaluationResult::MemoryLocation(location) => {
self.generate_memory_location(location, pt_regs_ptr, dwarf_type, status_ptr)
}
EvaluationResult::Optimized => {
debug!("Variable {} is optimized out", var_name);
// Return a placeholder value for optimized out variables
Ok(self.context.i64_type().const_zero().into())
}
EvaluationResult::Composite(members) => {
debug!(
"Variable {} is composite with {} members",
var_name,
members.len()
);
// For now, just return the first member if available
if let Some(first_member) = members.first() {
self.evaluate_result_to_llvm_value(
&first_member.location,
dwarf_type,
var_name,
pc_address,
status_ptr,
)
} else {
Ok(self.context.i64_type().const_zero().into())
}
}
}
}
/// Variant that allows passing an explicit module hint for offsets lookup
pub fn evaluation_result_to_address_with_hint(
&mut self,
evaluation_result: &EvaluationResult,
status_ptr: Option<PointerValue<'ctx>>,
module_hint: Option<&str>,
) -> Result<IntValue<'ctx>> {
// Policy note:
// - Link-time addresses (DW_OP_addr or constant-foldable address expressions) are
// always rebased using per-module section offsets (ASLR) to get a runtime address.
// - Runtime-derived addresses (register/stack-relative or computed via dereference)
// are used as-is and are NOT rebased.
// The caller signals which path we are on by providing the original evaluation_result.
let pt_regs_ptr = self.get_pt_regs_parameter()?;
// Default assumption: offsets are available unless a lookup proves otherwise.
self.store_offsets_found_const(true)?;
match evaluation_result {
EvaluationResult::MemoryLocation(LocationResult::Address(addr)) => {
// Unified: always attempt runtime rebasing via proc_module_offsets
let ctx = self.get_compile_time_context()?;
let module_for_offsets = module_hint
.map(|s| s.to_string())
.or_else(|| self.current_resolved_var_module_path.clone())
.unwrap_or_else(|| ctx.module_path.clone());
let st_code = self.section_code_for_address(&module_for_offsets, *addr);
let cookie = self.cookie_for_module_or_fallback(&module_for_offsets);
let link_val = self.context.i64_type().const_int(*addr, false);
let (rt_addr, found_flag) =
self.generate_runtime_address_from_offsets(link_val, st_code, cookie)?;
if let Some(sp) = status_ptr {
let is_miss = self
.builder
.build_int_compare(
inkwell::IntPredicate::EQ,
found_flag,
self.context.bool_type().const_zero(),
"is_off_miss",
)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
let cur_status = self
.builder
.build_load(self.context.i8_type(), sp, "cur_status")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
let is_ok = self
.builder
.build_int_compare(
inkwell::IntPredicate::EQ,
cur_status.into_int_value(),
self.context.i8_type().const_zero(),
"status_is_ok",
)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
let should_store = self
.builder
.build_and(is_miss, is_ok, "store_offsets_unavail")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
let new_status = self
.builder
.build_select(
should_store,
self.context
.i8_type()
.const_int(
ghostscope_protocol::VariableStatus::OffsetsUnavailable as u64,
false,
)
.into(),
cur_status,
"new_status",
)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
self.builder
.build_store(sp, new_status)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
}
self.store_offsets_found_flag(found_flag)?;
self.current_resolved_var_module_path = None;
Ok(rt_addr)
}
EvaluationResult::MemoryLocation(LocationResult::RegisterAddress {
register,
offset,
..
}) => {
let reg_val = self.load_register_value(*register, pt_regs_ptr)?;
if let BasicValueEnum::IntValue(reg_i) = reg_val {
if let Some(ofs) = offset {
let ofs_val = self.context.i64_type().const_int(*ofs as u64, true);
let sum = self
.builder
.build_int_add(reg_i, ofs_val, "addr_with_offset")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
Ok(sum)
} else {
Ok(reg_i)
}
} else {
Err(CodeGenError::RegisterMappingError(
"Register value is not integer".to_string(),
))
}
}
EvaluationResult::MemoryLocation(LocationResult::ComputedLocation { steps }) => {
// Try to fold constant-only address expressions (e.g., global + const offset)
// If foldable, treat as link-time address and apply ASLR offsets via map.
let mut const_stack: Vec<i64> = Vec::new();
let mut foldable = true;
for s in steps.iter() {
match s {
ComputeStep::PushConstant(v) => const_stack.push(*v),
ComputeStep::Add => {
if const_stack.len() >= 2 {
let b = const_stack.pop().unwrap();
let a = const_stack.pop().unwrap();
const_stack.push(a.saturating_add(b));
} else {
foldable = false;
break;
}
}
// Any register load or deref means runtime-derived address; not foldable
ComputeStep::LoadRegister(_) | ComputeStep::Dereference { .. } => {
foldable = false;
break;
}
_ => {
// Unknown/non-add op: treat as non-foldable
foldable = false;
break;
}
}
}
if foldable && const_stack.len() == 1 {
let link_addr_u = const_stack[0] as u64;
let ctx = self.get_compile_time_context()?;
let module_for_offsets = module_hint
.map(|s| s.to_string())
.or_else(|| self.current_resolved_var_module_path.clone())
.unwrap_or_else(|| ctx.module_path.clone());
let st_code = self.section_code_for_address(&module_for_offsets, link_addr_u);
let cookie = self.cookie_for_module_or_fallback(&module_for_offsets);
let link_val = self.context.i64_type().const_int(link_addr_u, false);
let (rt_addr, found_flag) =
self.generate_runtime_address_from_offsets(link_val, st_code, cookie)?;
if let Some(sp) = status_ptr {
let is_miss = self
.builder
.build_int_compare(
inkwell::IntPredicate::EQ,
found_flag,
self.context.bool_type().const_zero(),
"is_off_miss",
)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
let cur_status = self
.builder
.build_load(self.context.i8_type(), sp, "cur_status")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
let is_ok = self
.builder
.build_int_compare(
inkwell::IntPredicate::EQ,
cur_status.into_int_value(),
self.context.i8_type().const_zero(),
"status_is_ok",
)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
let should_store = self
.builder
.build_and(is_miss, is_ok, "store_offsets_unavail")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
let new_status = self
.builder
.build_select(
should_store,
self.context
.i8_type()
.const_int(
ghostscope_protocol::VariableStatus::OffsetsUnavailable
as u64,
false,
)
.into(),
cur_status,
"new_status",
)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
self.builder
.build_store(sp, new_status)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
}
self.current_resolved_var_module_path = None;
return Ok(rt_addr);
}
// Attempt: if steps start with PushConstant(base) and first dynamic op is Dereference
// (with no LoadRegister before it), apply ASLR offsets to base and continue
if let Some(ComputeStep::PushConstant(base_const)) = steps.first() {
// Scan until first Dereference or LoadRegister
let mut saw_reg = false;
let mut saw_deref = false;
for s in &steps[1..] {
match s {
ComputeStep::LoadRegister(_) => {
saw_reg = true;
break;
}
ComputeStep::Dereference { .. } => {
saw_deref = true;
break;
}
_ => {}
}
}
if saw_deref && !saw_reg {
let link_addr_u = *base_const as u64;
let ctx = self.get_compile_time_context()?;
let module_for_offsets = module_hint
.map(|s| s.to_string())
.or_else(|| self.current_resolved_var_module_path.clone())
.unwrap_or_else(|| ctx.module_path.clone());
let st_code =
self.section_code_for_address(&module_for_offsets, link_addr_u);
let cookie = self.cookie_for_module_or_fallback(&module_for_offsets);
let link_val = self.context.i64_type().const_int(link_addr_u, false);
let (rt, found_flag) =
self.generate_runtime_address_from_offsets(link_val, st_code, cookie)?;
if let Some(sp) = status_ptr {
let is_miss = self
.builder
.build_int_compare(
inkwell::IntPredicate::EQ,
found_flag,
self.context.bool_type().const_zero(),
"is_off_miss",
)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
let cur_status = self
.builder
.build_load(self.context.i8_type(), sp, "cur_status")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
let is_ok = self
.builder
.build_int_compare(
inkwell::IntPredicate::EQ,
cur_status.into_int_value(),
self.context.i8_type().const_zero(),
"status_is_ok",
)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
let should_store = self
.builder
.build_and(is_miss, is_ok, "store_offsets_unavail")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
let new_status = self
.builder
.build_select(
should_store,
self.context
.i8_type()
.const_int(
ghostscope_protocol::VariableStatus::OffsetsUnavailable
as u64,
false,
)
.into(),
cur_status,
"new_status",
)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
self.builder
.build_store(sp, new_status)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
}
// Execute remaining steps with rt pre-pushed as base
let rest = &steps[1..];
let val = self.generate_compute_steps(
rest,
pt_regs_ptr,
None,
status_ptr,
Some(rt),
)?;
if let BasicValueEnum::IntValue(i) = val {
return Ok(i);
} else {
return Err(CodeGenError::LLVMError(
"Computed location did not produce integer".to_string(),
));
}
}
}
// Fallback: execute steps at runtime and use the result directly (no offsets)
let val =
self.generate_compute_steps(steps, pt_regs_ptr, None, status_ptr, None)?;
if let BasicValueEnum::IntValue(i) = val {
Ok(i)
} else {
Err(CodeGenError::LLVMError(
"Computed location did not produce integer".to_string(),
))
}
}
_ => Err(CodeGenError::NotImplemented(
"Unable to compute address from evaluation result".to_string(),
)),
}
}
/// Convert DWARF type size to MemoryAccessSize
fn dwarf_type_to_memory_access_size(&self, dwarf_type: &TypeInfo) -> MemoryAccessSize {
let size = Self::get_dwarf_type_size(dwarf_type);
match size {
1 => MemoryAccessSize::U8,
2 => MemoryAccessSize::U16,
4 => MemoryAccessSize::U32,
8 => MemoryAccessSize::U64,
_ => MemoryAccessSize::U64, // Default to U64 for unknown sizes
}
}
/// Generate LLVM IR for direct value result
fn generate_direct_value(
&mut self,
direct: &DirectValueResult,
pt_regs_ptr: PointerValue<'ctx>,
) -> Result<BasicValueEnum<'ctx>> {
match direct {
DirectValueResult::Constant(value) => {
debug!("Generating constant: {}", value);
Ok(self
.context
.i64_type()
.const_int(*value as u64, true)
.into())
}
DirectValueResult::AbsoluteAddress(value) => {
debug!("Generating rebased absolute address: 0x{value:x}");
let module_hint = self.current_resolved_var_module_path.clone();
let status_ptr = if self.condition_context_active {
Some(self.get_or_create_cond_error_global())
} else {
None
};
let eval = ghostscope_dwarf::EvaluationResult::MemoryLocation(
ghostscope_dwarf::LocationResult::Address(*value),
);
self.evaluation_result_to_address_with_hint(
&eval,
status_ptr,
module_hint.as_deref(),
)
.map(Into::into)
}
DirectValueResult::ImplicitValue(bytes) => {
debug!("Generating implicit value: {} bytes", bytes.len());
// Convert bytes to integer value (little-endian)
let mut value: u64 = 0;
for (i, &byte) in bytes.iter().enumerate().take(8) {
value |= (byte as u64) << (i * 8);
}
Ok(self.context.i64_type().const_int(value, false).into())
}
DirectValueResult::RegisterValue(reg_num) => {
debug!("Generating register value: {}", reg_num);
let reg_value = self.load_register_value(*reg_num, pt_regs_ptr)?;
Ok(reg_value)
}
DirectValueResult::ComputedValue { steps, result_size } => {
debug!("Generating computed value: {} steps", steps.len());
let status_ptr = if self.condition_context_active {
Some(self.get_or_create_cond_error_global())
} else {
None
};
self.generate_compute_steps(
steps,
pt_regs_ptr,
Some(*result_size),
status_ptr,
None,
)
}
}
}
/// Generate LLVM IR for memory location result
fn generate_memory_location(
&mut self,
location: &LocationResult,
pt_regs_ptr: PointerValue<'ctx>,
dwarf_type: &TypeInfo,
status_ptr: Option<PointerValue<'ctx>>,
) -> Result<BasicValueEnum<'ctx>> {
match location {
// Policy note:
// We decide ASLR rebasing based on the DWARF evaluation RESULT SHAPE, not a
// "global variable" tag. Whenever DWARF yields a link-time address
// (LocationResult::Address) — including file-scope globals, static locals,
// rodata/data/bss, or any constant-folded address — we MUST apply per-module
// section offsets (.text/.rodata/.data/.bss) to obtain the runtime address.
// Conversely, for runtime-derived addresses (RegisterAddress or computed from
// registers/dereferences), we DO NOT rebase.
LocationResult::Address(addr) => {
debug!("Generating absolute address: 0x{:x}", addr);
// Convert link-time address to runtime address using ASLR offsets when available
let module_hint = self.current_resolved_var_module_path.clone();
let runtime_status_ptr = if self.condition_context_active {
Some(self.get_or_create_cond_error_global())
} else {
status_ptr
};
let eval = ghostscope_dwarf::EvaluationResult::MemoryLocation(
ghostscope_dwarf::LocationResult::Address(*addr),
);
let rt_addr = self.evaluation_result_to_address_with_hint(
&eval,
runtime_status_ptr,
module_hint.as_deref(),
)?;
// Aggregate types (struct/union/array) are represented as pointers in expressions
if self.is_aggregate_type(dwarf_type) {
let ptr_ty = self.context.ptr_type(inkwell::AddressSpace::default());
let as_ptr = self
.builder
.build_int_to_ptr(rt_addr, ptr_ty, "aggregate_addr_as_ptr")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
return Ok(as_ptr.into());
}
// Use DWARF type size for memory access
let access_size = self.dwarf_type_to_memory_access_size(dwarf_type);
if self.condition_context_active {
self.generate_memory_read_with_status(rt_addr, access_size)
} else {
self.generate_memory_read(rt_addr, access_size, status_ptr)
}
}
LocationResult::RegisterAddress {
register,
offset,
size,
} => {
debug!(
"Generating register address: reg{} {:+}",
register,
offset.unwrap_or(0)
);
// Load register value
let reg_value = self.load_register_value(*register, pt_regs_ptr)?;
// Add offset if present
let final_addr = if let Some(offset) = offset {
let offset_value = self.context.i64_type().const_int(*offset as u64, true);
if let BasicValueEnum::IntValue(reg_int) = reg_value {
self.builder
.build_int_add(reg_int, offset_value, "addr_with_offset")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?
} else {
return Err(CodeGenError::RegisterMappingError(
"Register value is not integer".to_string(),
));
}
} else if let BasicValueEnum::IntValue(reg_int) = reg_value {
reg_int
} else {
return Err(CodeGenError::RegisterMappingError(
"Register value is not integer".to_string(),
));
};
// Aggregate types: return pointer instead of reading as scalar
if self.is_aggregate_type(dwarf_type) {
let ptr_ty = self.context.ptr_type(inkwell::AddressSpace::default());
let as_ptr = self
.builder
.build_int_to_ptr(final_addr, ptr_ty, "aggregate_addr_as_ptr")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
return Ok(as_ptr.into());
}
// Determine memory access size - prefer LocationResult size if available, otherwise use DWARF type
let access_size = size
.map(|s| match s {
1 => MemoryAccessSize::U8,
2 => MemoryAccessSize::U16,
4 => MemoryAccessSize::U32,
_ => MemoryAccessSize::U64,
})
.unwrap_or_else(|| self.dwarf_type_to_memory_access_size(dwarf_type));
if self.condition_context_active {
self.generate_memory_read_with_status(final_addr, access_size)
} else {
self.generate_memory_read(final_addr, access_size, status_ptr)
}
}
LocationResult::ComputedLocation { steps } => {
debug!("Generating computed location: {} steps", steps.len());
// Execute steps to compute the address
let runtime_status_ptr = if self.condition_context_active {
Some(self.get_or_create_cond_error_global())
} else {
status_ptr
};
let addr_value = self.generate_compute_steps(
steps,
pt_regs_ptr,
None,
runtime_status_ptr,
None,
)?;
if let BasicValueEnum::IntValue(addr) = addr_value {
// For aggregate types, return pointer to address instead of loading a value
if self.is_aggregate_type(dwarf_type) {
let ptr_ty = self.context.ptr_type(inkwell::AddressSpace::default());
let as_ptr = self
.builder
.build_int_to_ptr(addr, ptr_ty, "aggregate_addr_as_ptr")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
return Ok(as_ptr.into());
}
// Use DWARF type size for memory access
let access_size = self.dwarf_type_to_memory_access_size(dwarf_type);
if self.condition_context_active {
self.generate_memory_read_with_status(addr, access_size)
} else {
self.generate_memory_read(addr, access_size, status_ptr)
}
} else {
Err(CodeGenError::LLVMError(
"Address computation must return integer".to_string(),
))
}
}
}
}
/// Execute a sequence of compute steps
fn generate_compute_steps(
&mut self,
steps: &[ComputeStep],
pt_regs_ptr: PointerValue<'ctx>,
_result_size: Option<MemoryAccessSize>,
status_ptr: Option<PointerValue<'ctx>>,
initial_top: Option<IntValue<'ctx>>,
) -> Result<BasicValueEnum<'ctx>> {
// Implement stack-based computation
let mut stack: Vec<IntValue<'ctx>> = Vec::new();
// Track a runtime null-pointer flag from dereference steps; when true, subsequent
// arithmetic will be masked to zero to avoid reads at small offsets from NULL.
let mut deref_null_flag: Option<inkwell::values::IntValue> = None;
if let Some(top) = initial_top {
stack.push(top);
}
for step in steps {
match step {
ComputeStep::LoadRegister(reg_num) => {
let reg_value = self.load_register_value(*reg_num, pt_regs_ptr)?;
if let BasicValueEnum::IntValue(int_val) = reg_value {
stack.push(int_val);
} else {
return Err(CodeGenError::RegisterMappingError(format!(
"Register {reg_num} did not return integer value"
)));
}
}
ComputeStep::PushConstant(value) => {
let const_val = self.context.i64_type().const_int(*value as u64, true);
stack.push(const_val);
}
ComputeStep::Add => {
if let (Some(b), Some(a)) = (stack.pop(), stack.pop()) {
let sum_val = self
.builder
.build_int_add(a, b, "add")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
if let Some(nf) = deref_null_flag {
let masked_bv = self
.builder
.build_select::<inkwell::values::BasicValueEnum<'ctx>, _>(
nf,
self.context.i64_type().const_zero().into(),
sum_val.into(),
"add_masked",
)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
stack.push(masked_bv.into_int_value());
} else {
stack.push(sum_val);
}
} else {
return Err(CodeGenError::LLVMError(
"Stack underflow in Add".to_string(),
));
}
}
ComputeStep::Sub => {
if let (Some(b), Some(a)) = (stack.pop(), stack.pop()) {
let result = self
.builder
.build_int_sub(a, b, "sub")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
stack.push(result);
} else {
return Err(CodeGenError::LLVMError(
"Stack underflow in Sub".to_string(),
));
}
}
ComputeStep::Mul => {
if let (Some(b), Some(a)) = (stack.pop(), stack.pop()) {
let result = self
.builder
.build_int_mul(a, b, "mul")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
stack.push(result);
} else {
return Err(CodeGenError::LLVMError(
"Stack underflow in Mul".to_string(),
));
}
}
ComputeStep::Div => {
if let (Some(b), Some(a)) = (stack.pop(), stack.pop()) {
let result = self
.builder
.build_int_signed_div(a, b, "div")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
stack.push(result);
} else {
return Err(CodeGenError::LLVMError(
"Stack underflow in Div".to_string(),
));
}
}
ComputeStep::And => {
if let (Some(b), Some(a)) = (stack.pop(), stack.pop()) {
let result = self
.builder
.build_and(a, b, "and")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
stack.push(result);
} else {
return Err(CodeGenError::LLVMError(
"Stack underflow in BitwiseAnd".to_string(),
));
}
}
ComputeStep::Or => {
if let (Some(b), Some(a)) = (stack.pop(), stack.pop()) {
let result = self
.builder
.build_or(a, b, "or")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
stack.push(result);
} else {
return Err(CodeGenError::LLVMError(
"Stack underflow in BitwiseOr".to_string(),
));
}
}
ComputeStep::Xor => {
if let (Some(b), Some(a)) = (stack.pop(), stack.pop()) {
let result = self
.builder
.build_xor(a, b, "xor")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
stack.push(result);
} else {
return Err(CodeGenError::LLVMError(
"Stack underflow in BitwiseXor".to_string(),
));
}
}
ComputeStep::Shl => {
if let (Some(b), Some(a)) = (stack.pop(), stack.pop()) {
let result = self
.builder
.build_left_shift(a, b, "shl")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
stack.push(result);
} else {
return Err(CodeGenError::LLVMError(
"Stack underflow in ShiftLeft".to_string(),
));
}
}
ComputeStep::Shr => {
if let (Some(b), Some(a)) = (stack.pop(), stack.pop()) {
let result = self
.builder
.build_right_shift(a, b, false, "shr")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
stack.push(result);
} else {
return Err(CodeGenError::LLVMError(
"Stack underflow in ShiftRight".to_string(),
));
}
}
ComputeStep::Dereference { size } => {
if let Some(addr) = stack.pop() {
// Null guard: if addr == 0, set NullDeref (if status_ptr provided and current is Ok)
let zero64 = self.context.i64_type().const_zero();
let is_null = self
.builder
.build_int_compare(
inkwell::IntPredicate::EQ,
addr,
zero64,
"is_null_deref",
)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
let cur_fn = self
.builder
.get_insert_block()
.unwrap()
.get_parent()
.unwrap();
let null_bb = self.context.append_basic_block(cur_fn, "deref_null");
let read_bb = self.context.append_basic_block(cur_fn, "deref_read");
let cont_bb = self.context.append_basic_block(cur_fn, "deref_cont");
self.builder
.build_conditional_branch(is_null, null_bb, read_bb)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
// Null path: optionally set status=NullDeref if currently Ok, branch to cont
self.builder.position_at_end(null_bb);
let null_val = self.context.i64_type().const_zero();
if let Some(sp) = status_ptr {
let cur_status = self
.builder
.build_load(self.context.i8_type(), sp, "cur_status")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?
.into_int_value();
let is_ok = self
.builder
.build_int_compare(
inkwell::IntPredicate::EQ,
cur_status,
self.context.i8_type().const_zero(),
"status_is_ok",
)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
let then_val = self.context.i8_type().const_int(
ghostscope_protocol::VariableStatus::NullDeref as u64,
false,
);
let new_status_bv = self
.builder
.build_select::<inkwell::values::BasicValueEnum<'ctx>, _>(
is_ok,
then_val.into(),
cur_status.into(),
"new_status",
)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
self.builder
.build_store(sp, new_status_bv)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
}
self.builder
.build_unconditional_branch(cont_bb)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
// Read path: load pointer-sized value into tmp then branch to cont
self.builder.position_at_end(read_bb);
let access_size = *size;
let loaded_bv = if self.condition_context_active {
self.generate_memory_read_with_status(addr, access_size)?
} else {
self.generate_memory_read(addr, access_size, status_ptr)?
};
let loaded_int = if let BasicValueEnum::IntValue(int_val) = loaded_bv {
int_val
} else {
return Err(CodeGenError::LLVMError(
"Memory load did not return integer".to_string(),
));
};
let value_block = self.builder.get_insert_block().ok_or_else(|| {
CodeGenError::LLVMError(
"No insertion block after dereference read".to_string(),
)
})?;
self.builder
.build_unconditional_branch(cont_bb)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
// Continue at cont: create PHI to merge null/read values, push once
self.builder.position_at_end(cont_bb);
let phi = self
.builder
.build_phi(self.context.i64_type(), "deref_phi")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
phi.add_incoming(&[(&null_val, null_bb), (&loaded_int, value_block)]);
let merged = phi.as_basic_value().into_int_value();
// Update null flag based on loaded pointer value being zero
let is_zero_ptr = self
.builder
.build_int_compare(
inkwell::IntPredicate::EQ,
merged,
self.context.i64_type().const_zero(),
"is_zero_ptr",
)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
deref_null_flag = Some(match deref_null_flag {
Some(prev) => self
.builder
.build_or(prev, is_zero_ptr, "null_or")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?,
None => is_zero_ptr,
});
if let (Some(sp), Some(nf)) = (status_ptr, deref_null_flag) {
// Only store NullDeref if currently OK and nf is true
let cur_status = self
.builder
.build_load(self.context.i8_type(), sp, "cur_status")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?
.into_int_value();
let is_ok = self
.builder
.build_int_compare(
inkwell::IntPredicate::EQ,
cur_status,
self.context.i8_type().const_zero(),
"status_is_ok2",
)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
let should_store = self
.builder
.build_and(is_ok, nf, "store_null_deref_from_ptr")
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
let then_val = self.context.i8_type().const_int(
ghostscope_protocol::VariableStatus::NullDeref as u64,
false,
);
let new_status_bv = self
.builder
.build_select::<inkwell::values::BasicValueEnum<'ctx>, _>(
should_store,
then_val.into(),
cur_status.into(),
"new_status2",
)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
self.builder
.build_store(sp, new_status_bv)
.map_err(|e| CodeGenError::LLVMError(e.to_string()))?;
}
stack.push(merged);
} else {
return Err(CodeGenError::LLVMError(
"Stack underflow in LoadMemory".to_string(),
));
}
}
ComputeStep::EntryValueLookup {
caller_pc_steps,
cases,
} => {
let value = self.generate_entry_value_lookup(