-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathscript_execution.rs
More file actions
1900 lines (1622 loc) · 61.8 KB
/
script_execution.rs
File metadata and controls
1900 lines (1622 loc) · 61.8 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
//! Script execution integration tests
//!
//! Tests for ghostscope script execution and tracing functionality.
//! Assumes tests are run with sudo permissions for eBPF attachment.
//!
//! Concurrency note: these tests intentionally exercise multiple scripts
//! against a single long-lived sample_program process (per optimization
//! level). This is by design to validate real-world multi-attachment
//! scenarios and reduce test startup overhead. Do not serialize this file.
mod common;
use common::{init, OptimizationLevel, FIXTURES};
use lazy_static::lazy_static;
use std::collections::HashMap;
use std::sync::{Arc, Once};
use tokio::sync::RwLock;
// Global test program management
lazy_static! {
// Maintain one process per optimization level to avoid cross-test interference.
static ref GLOBAL_TEST_MANAGER: Arc<RwLock<HashMap<OptimizationLevel, GlobalTestProcess>>> =
Arc::new(RwLock::new(HashMap::new()));
}
struct GlobalTestProcess {
target: common::targets::TargetHandle,
optimization_level: OptimizationLevel,
}
impl GlobalTestProcess {
async fn start_with_opt(opt_level: OptimizationLevel) -> anyhow::Result<Self> {
println!(
"🚀 Starting global sample_program ({})",
opt_level.description()
);
let target = common::targets::TargetLauncher::sample_program_with_opt(opt_level)
.spawn()
.await?;
let host_pid = target.host_pid();
let visible_pid =
target.visible_pid_from(&common::sandbox::SandboxHandle::default_ghostscope()?)?;
println!(
"✓ Started global sample_program ({}) with host_pid={} visible_pid={}",
opt_level.description(),
host_pid,
visible_pid
);
Ok(Self {
target,
optimization_level: opt_level,
})
}
fn host_pid(&self) -> u32 {
self.target.host_pid()
}
fn visible_pid(&self) -> anyhow::Result<u32> {
self.target
.visible_pid_from(&common::sandbox::SandboxHandle::default_ghostscope()?)
}
fn target(&self) -> &common::targets::TargetHandle {
&self.target
}
async fn terminate(self) -> anyhow::Result<()> {
println!(
"🛑 Terminating global sample_program ({}, host PID: {})",
self.optimization_level.description(),
self.host_pid()
);
self.target.terminate().await?;
println!(
"✓ Global sample_program ({}) terminated",
self.optimization_level.description()
);
Ok(())
}
}
// Get or start the global test process with specific optimization level
async fn get_global_test_pid_with_opt(opt_level: OptimizationLevel) -> anyhow::Result<u32> {
let manager = GLOBAL_TEST_MANAGER.clone();
// Fast path: check if we already have a live process for this opt level
{
let read_guard = manager.read().await;
if let Some(process) = read_guard.get(&opt_level) {
if common::host_pid_is_running(process.host_pid()) {
return process.visible_pid();
}
}
}
// Slow path: create or replace the entry for this opt level
let mut write_guard = manager.write().await;
// Double-check under write lock in case another task started it
if let Some(process) = write_guard.get(&opt_level) {
if common::host_pid_is_running(process.host_pid()) {
return process.visible_pid();
}
}
// If an old process exists for this opt level, remove it first (drop lock before awaiting)
let old_proc = write_guard.remove(&opt_level);
drop(write_guard);
if let Some(old) = old_proc {
let _ = old.terminate().await;
}
// Start new process with the requested optimization level
let new_process = GlobalTestProcess::start_with_opt(opt_level).await?;
let pid = new_process.visible_pid()?;
// Re-acquire write lock to insert the new process
let mut write_guard = manager.write().await;
write_guard.insert(opt_level, new_process);
Ok(pid)
}
async fn get_global_test_target_with_opt(
opt_level: OptimizationLevel,
) -> anyhow::Result<common::targets::TargetHandle> {
let _ = get_global_test_pid_with_opt(opt_level).await?;
let manager = GLOBAL_TEST_MANAGER.clone();
let read_guard = manager.read().await;
let process = read_guard.get(&opt_level).ok_or_else(|| {
anyhow::anyhow!("global test target missing for {}", opt_level.description())
})?;
Ok(process.target().clone())
}
// Get or start the global test process (defaults to Debug optimization)
// Cleanup function to be called when tests finish
pub async fn cleanup_global_test_process() -> anyhow::Result<()> {
let manager = GLOBAL_TEST_MANAGER.clone();
let mut write_guard = manager.write().await;
// Terminate all managed processes (for every optimization level)
let processes: Vec<GlobalTestProcess> = write_guard.drain().map(|(_, p)| p).collect();
drop(write_guard);
for proc in processes.into_iter() {
let _ = proc.terminate().await;
}
Ok(())
}
#[tokio::test]
async fn test_void_pointer_addition_prints_address() -> anyhow::Result<()> {
// Verify: for sink_void(const void* p), p+1 prints an address (fallback path)
init();
ensure_global_cleanup_registered();
let opt_level = OptimizationLevel::Debug;
let _ = get_global_test_pid_with_opt(opt_level).await?;
let script_content = r#"
trace sink_void {
print p + 1;
}
"#;
let (exit_code, stdout, stderr) =
run_ghostscope_with_script_opt(script_content, 4, opt_level).await?;
assert_eq!(
exit_code, 0,
"unexpected error: stderr={stderr}\nstdout={stdout}"
);
// Expect something like: (p+1) = 0x... or plain 0x... (void*)
// This covers the AddressValue path rendered via ComplexFormat
let mut saw_addr = false;
for line in stdout.lines() {
let t = line.trim();
if (t.starts_with("(p+1) = ") && t.contains("0x"))
|| (t.starts_with("0x") && t.contains("(void*)"))
{
saw_addr = true;
break;
}
}
assert!(
saw_addr,
"expected (p+1) to print an address.\nSTDOUT: {stdout}\nSTDERR: {stderr}"
);
Ok(())
}
#[tokio::test]
async fn test_struct_pointer_addition_scales_by_type_size() -> anyhow::Result<()> {
// Verify: on print_record(const DataRecord* record), (record+1) and (record+2)
// have addresses separated by sizeof(DataRecord) (expected 48 bytes on x86_64 with current layout).
// We avoid relying on successful reads; we only compare addresses when read fails (errno=-14).
init();
ensure_global_cleanup_registered();
let opt_level = OptimizationLevel::Debug;
let _ = get_global_test_pid_with_opt(opt_level).await?;
let script_content = r#"
trace print_record {
print record + 1;
print record + 2;
}
"#;
let (exit_code, stdout, stderr) =
run_ghostscope_with_script_opt(script_content, 5, opt_level).await?;
// If attach fails due to sandbox (BPF_PROG_LOAD), skip to avoid false negatives in CI
if exit_code != 0 && stderr.contains("BPF_PROG_LOAD") {
return Ok(());
}
assert_eq!(
exit_code, 0,
"unexpected error: stderr={stderr}\nstdout={stdout}"
);
// Gather addresses from failure lines for (record+1) and (record+2)
let mut addr1: Option<u64> = None;
let mut addr2: Option<u64> = None;
for line in stdout.lines() {
let t = line.trim();
if t.starts_with("(record+1) = ") || t.starts_with("(record + 1) = ") {
if let Some(ix) = t.rfind("0x") {
let mut j = ix + 2;
let bytes = t.as_bytes();
while j < t.len() && bytes[j].is_ascii_hexdigit() {
j += 1;
}
if j > ix + 2 {
if let Ok(v) = u64::from_str_radix(&t[ix + 2..j], 16) {
addr1 = Some(v);
}
}
}
}
if t.starts_with("(record+2) = ") || t.starts_with("(record + 2) = ") {
if let Some(ix) = t.rfind("0x") {
let mut j = ix + 2;
let bytes = t.as_bytes();
while j < t.len() && bytes[j].is_ascii_hexdigit() {
j += 1;
}
if j > ix + 2 {
if let Ok(v) = u64::from_str_radix(&t[ix + 2..j], 16) {
addr2 = Some(v);
}
}
}
}
}
if let (Some(a1), Some(a2)) = (addr1, addr2) {
// Expected sizeof(DataRecord) = 48 bytes with current layout (int(4)+name[32]+padding(4)+double(8))
let delta = a2.wrapping_sub(a1);
assert_eq!(
delta, 48,
"expected address delta sizeof(DataRecord)=48 bytes (got {delta}).\nSTDOUT: {stdout}\nSTDERR: {stderr}"
);
} else {
// If we didn't observe failure lines with addresses, we cannot assert safely here.
// Consider success in this scenario to avoid flaky behavior.
}
Ok(())
}
#[tokio::test]
async fn test_special_pid_in_if_condition() -> anyhow::Result<()> {
init();
ensure_global_cleanup_registered();
let opt_level = OptimizationLevel::Debug;
let test_pid = get_global_test_pid_with_opt(opt_level).await?;
// Use $input_pid in an expression: it should equal the PID passed through -p.
let script_content = format!(
"trace sample_program.c:16 {{\n if $input_pid == {test_pid} {{ print \"PID_OK\"; }} else {{ print \"PID_BAD\"; }}\n}}\n"
);
let (exit_code, stdout, stderr) =
run_ghostscope_with_script_opt(&script_content, 3, opt_level).await?;
assert_eq!(exit_code, 0, "stderr={stderr}");
assert!(
stdout.contains("PID_OK"),
"Expected PID_OK in output. STDOUT: {stdout}"
);
Ok(())
}
#[tokio::test]
async fn test_special_tid_and_timestamp_print() -> anyhow::Result<()> {
init();
ensure_global_cleanup_registered();
let opt_level = OptimizationLevel::Debug;
let _ = get_global_test_pid_with_opt(opt_level).await?;
// Just print them to ensure they compile, evaluate and render
let script_content = r#"
trace sample_program.c:16 {
print "TST:{} {}", $tid, $timestamp;
}
"#;
let (exit_code, stdout, stderr) =
run_ghostscope_with_script_opt(script_content, 3, opt_level).await?;
assert_eq!(exit_code, 0, "stderr={stderr}");
assert!(
stdout.contains("TST:"),
"Expected TST: with tid/timestamp in output. STDOUT: {stdout}"
);
Ok(())
}
// Global cleanup registration - only runs once when the first test calls it
static GLOBAL_CLEANUP_REGISTERED: Once = Once::new();
fn ensure_global_cleanup_registered() {
GLOBAL_CLEANUP_REGISTERED.call_once(|| {
// Use atexit to ensure cleanup runs when the test binary exits
extern "C" fn cleanup_on_exit() {
println!("🧹 Global test cleanup: All tests finished, cleaning up...");
// Kill any remaining sample_program processes
let _pkill_result = std::process::Command::new("pkill")
.args(["-f", "sample_program"]) // pass array by value to avoid needless borrow
.status()
.is_ok();
// Clean up sample_program build files
let fixtures_path =
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
let sample_program_dir = fixtures_path.join("sample_program");
println!("🧹 Running make clean in sample_program directory...");
let clean_result = std::process::Command::new("make")
.arg("clean")
.current_dir(sample_program_dir)
.output();
match clean_result {
Ok(output) => {
if output.status.success() {
println!("✓ Successfully cleaned sample_program build files");
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
println!("⚠️ Make clean failed: {stderr}");
}
}
Err(e) => {
println!("⚠️ Failed to run make clean: {e}");
}
}
println!("🧹 Global cleanup completed");
}
unsafe {
libc::atexit(cleanup_on_exit);
}
println!("✓ Global cleanup handler registered");
});
}
/// Helper to run ghostscope with script and capture results with specific optimization level
/// For failing cases (syntax errors, etc.), this will return quickly with exit code != 0
/// For successful cases, this will run for timeout_secs, collect output, then terminate the process
async fn run_ghostscope_with_script_opt(
script_content: &str,
timeout_secs: u64,
opt_level: OptimizationLevel,
) -> anyhow::Result<(i32, String, String)> {
// Get PID of running sample_program with specific optimization level
let test_pid = get_global_test_pid_with_opt(opt_level).await?;
println!(
"🔍 Running ghostscope with {} binary (PID: {})",
opt_level.description(),
test_pid
);
let target = get_global_test_target_with_opt(opt_level).await?;
common::runner::GhostscopeRunner::new()
.with_script(script_content)
.attach_to(&target)
.timeout_secs(timeout_secs)
.enable_sysmon_shared_lib(false)
.run()
.await
}
/// Helper to run ghostscope with script and capture results (defaults to Debug optimization)
/// For failing cases (syntax errors, etc.), this will return quickly with exit code != 0
/// For successful cases, this will run for timeout_secs, collect output, then terminate the process
async fn run_ghostscope_with_script(
script_content: &str,
timeout_secs: u64,
) -> anyhow::Result<(i32, String, String)> {
run_ghostscope_with_script_opt(script_content, timeout_secs, OptimizationLevel::Debug).await
}
#[tokio::test]
async fn test_capture_len_uses_scalar_script_var_from_dwarf_expr() -> anyhow::Result<()> {
init();
let binary_path = FIXTURES.get_test_binary("sample_program")?;
let analyzer = ghostscope_dwarf::DwarfAnalyzer::from_exec_path(&binary_path)
.await
.map_err(|e| anyhow::anyhow!("failed to load DWARF for sample_program: {e}"))?;
let script_content = r#"
trace sample_lib.c:45 {
let n = len;
print "LEN_MSG={:s.n$}", str;
}
"#;
let compile_options = ghostscope_compiler::CompileOptions {
binary_path_hint: Some(binary_path.to_string_lossy().into_owned()),
..Default::default()
};
let result = ghostscope_compiler::compile_script(
script_content,
&analyzer,
None,
Some(1),
&compile_options,
)
.map_err(|e| anyhow::anyhow!("compile_script failed: {e}"))?;
assert!(
!result.uprobe_configs.is_empty(),
"expected at least one compiled uprobe config"
);
Ok(())
}
#[tokio::test]
async fn test_logical_or_short_circuit_chain() -> anyhow::Result<()> {
init();
ensure_global_cleanup_registered();
// Attach to a hot function so we get a few events quickly
let script_content = r#"
trace calculate_something {
// Exercise chained OR; final should be true
print (0 || 0 || 1);
// Exercise chained OR; final should be false
print (0 || 0 || 0);
}
"#;
let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 5).await?;
assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");
// Expect to observe both true and false lines at least once
let saw_true = stdout.contains("true");
let saw_false = stdout.contains("false");
assert!(
saw_true,
"Expected at least one true result. STDOUT: {stdout}"
);
assert!(
saw_false,
"Expected at least one false result. STDOUT: {stdout}"
);
Ok(())
}
#[tokio::test]
async fn test_memcmp_rejects_script_pointer_variable_e2e() -> anyhow::Result<()> {
init();
ensure_global_cleanup_registered();
// Using a script pointer variable as memcmp arg must fail at compile time now.
let script_content = r#"
trace calculate_something {
let p = "A";
if memcmp(p, hex("41"), 1) { print "OK"; } else { print "NO"; }
}
"#;
let (exit_code, _stdout, stderr) = run_ghostscope_with_script(script_content, 2).await?;
assert!(
exit_code != 0,
"expected non-zero exit due to compile error; stderr={stderr}"
);
// Expect the consolidated failed-targets banner with the pointer/address type error and tip
let has_banner = stderr.contains("No uprobe configurations created")
|| stderr.contains("Script compilation failed");
let has_failed_targets = stderr.contains("Failed targets:");
let has_reason = stderr.contains("expression is not a pointer/address");
let has_tip = stderr.contains("Tip: fix the reported compile-time errors above");
assert!(
has_banner && has_failed_targets && has_reason && has_tip,
"Expected failed-targets details with pointer/address reason and tip. stderr={stderr}"
);
Ok(())
}
#[tokio::test]
async fn test_pointer_ordered_comparison_is_rejected_e2e() -> anyhow::Result<()> {
init();
ensure_global_cleanup_registered();
// Ordered comparisons on pointers/addresses (<, <=, >, >=) are forbidden at compile time.
// process_data(const char* message) provides a pointer parameter for this check.
let script_content = r#"
trace process_data {
if message > 0 { print "BAD"; }
}
"#;
let (exit_code, _stdout, stderr) = run_ghostscope_with_script(script_content, 2).await?;
assert!(
exit_code != 0,
"expected non-zero exit due to compile error; stderr={stderr}"
);
// Expect banner + friendly pointer-ordered-comparison message
let has_banner = stderr.contains("No uprobe configurations created")
|| stderr.contains("Script compilation failed");
let has_reason =
stderr.contains("Pointer ordered comparison ('<', '<=', '>', '>=') is not supported");
assert!(
has_banner && has_reason,
"Expected pointer ordered comparison rejection with banner. stderr={stderr}"
);
Ok(())
}
#[tokio::test]
async fn test_pointer_addition_print_reads_element_at_offset() -> anyhow::Result<()> {
// Verify: print activity + 1; where activity: const char* in log_activity
// Should move by sizeof(char) and print the byte at new address (expected 'a' from "main_loop").
init();
ensure_global_cleanup_registered();
let opt_level = OptimizationLevel::Debug;
let _ = get_global_test_pid_with_opt(opt_level).await?;
let script_content = r#"
trace log_activity {
print activity + 1;
}
"#;
let (exit_code, stdout, stderr) =
run_ghostscope_with_script_opt(script_content, 4, opt_level).await?;
assert_eq!(
exit_code, 0,
"unexpected error: stderr={stderr}\nstdout={stdout}"
);
// Expect at least one line like: "(activity+1) = <value>" or "activity + 1 = <value>"
// Accept either numeric '97' or "'a'" depending on encoding handling.
let mut matched = false;
for line in stdout.lines() {
let t = line.trim();
let is_name = t.starts_with("(activity+1) = ") || t.starts_with("activity + 1 = ");
if is_name && (t.ends_with("97") || t.ends_with("'a'")) {
matched = true;
break;
}
}
assert!(
matched,
"expected activity + 1 to print 'a' (97).\nSTDOUT: {stdout}\nSTDERR: {stderr}"
);
Ok(())
}
#[tokio::test]
async fn test_pointer_addition_scales_on_int_array() -> anyhow::Result<()> {
// Verify: on calculate_average(int* numbers, int count), numbers+1 reads the 2nd int (20), numbers+2 reads 3rd (30)
init();
ensure_global_cleanup_registered();
let opt_level = OptimizationLevel::Debug;
let _ = get_global_test_pid_with_opt(opt_level).await?;
let script_content = r#"
trace sample_program.c:42 {
print numbers + 1;
print numbers + 2;
}
"#;
let (exit_code, stdout, stderr) =
run_ghostscope_with_script_opt(script_content, 5, opt_level).await?;
assert_eq!(
exit_code, 0,
"unexpected error: stderr={stderr}\nstdout={stdout}"
);
let mut saw_20 = false;
let mut saw_30 = false;
let mut addr1: Option<u64> = None;
let mut addr2: Option<u64> = None;
for line in stdout.lines() {
let t = line.trim();
if t.starts_with("(numbers+1) = ") {
if t.ends_with("20") {
saw_20 = true;
}
if let Some(ix) = t.rfind("0x") {
let mut j = ix + 2;
let bytes = t.as_bytes();
while j < t.len() && bytes[j].is_ascii_hexdigit() {
j += 1;
}
if j > ix + 2 {
if let Ok(v) = u64::from_str_radix(&t[ix + 2..j], 16) {
addr1 = Some(v);
}
}
}
}
if t.starts_with("(numbers+2) = ") {
if t.ends_with("30") {
saw_30 = true;
}
if let Some(ix) = t.rfind("0x") {
let mut j = ix + 2;
let bytes = t.as_bytes();
while j < t.len() && bytes[j].is_ascii_hexdigit() {
j += 1;
}
if j > ix + 2 {
if let Ok(v) = u64::from_str_radix(&t[ix + 2..j], 16) {
addr2 = Some(v);
}
}
}
}
}
if !(saw_20 && saw_30) {
if let (Some(a1), Some(a2)) = (addr1, addr2) {
assert_eq!(
a2.wrapping_sub(a1),
4,
"expected address delta 4 bytes.\nSTDOUT: {stdout}\nSTDERR: {stderr}"
);
} else {
panic!("expected (numbers+1)=20 and (numbers+2)=30, or address delta=4.\nSTDOUT: {stdout}\nSTDERR: {stderr}");
}
}
Ok(())
}
#[tokio::test]
async fn test_string_variable_copy_allowed_e2e() -> anyhow::Result<()> {
init();
ensure_global_cleanup_registered();
let script_content = r#"
trace calculate_something {
let s = "A";
let p = s;
print p;
}
"#;
let (exit_code, _stdout, stderr) = run_ghostscope_with_script(script_content, 5).await?;
assert_eq!(exit_code, 0, "unexpected error: stderr={stderr}");
Ok(())
}
#[tokio::test]
async fn test_assignment_is_rejected_with_friendly_message_e2e() -> anyhow::Result<()> {
init();
ensure_global_cleanup_registered();
// Immutable variables: reject assignment 'a = ...' with friendly error
let script_content = r#"
trace calculate_something {
let a = G_STATE.lib;
a = G_STATE;
if memcmp(a, hex("00"), 1) { print "A"; }
else if memcmp(gm, hex("48"), 1) { print "B"; }
else { print "C"; }
}
"#;
let (exit_code, _stdout, stderr) = run_ghostscope_with_script(script_content, 2).await?;
assert!(
exit_code != 0,
"expected compile-time error; stderr={stderr}"
);
assert!(
stderr.contains("Assignment is not supported: variables are immutable"),
"stderr should contain friendly assignment error. stderr={stderr}"
);
Ok(())
}
#[tokio::test]
async fn test_logical_mixed_precedence() -> anyhow::Result<()> {
init();
ensure_global_cleanup_registered();
// Validate precedence: && has higher precedence than ||
// (1 || 0 && 0) => 1 || (0 && 0) => true
// (0 || 1 && 0) => 0 || (1 && 0) => false
let script_content = r#"
trace calculate_something {
print "MIX:{}|{}", (1 || 0 && 0), (0 || 1 && 0);
}
"#;
let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 5).await?;
assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");
// Look for a line like: MIX:true|false
let expected = "MIX:true|false";
assert!(
stdout.contains(expected),
"Expected \"{expected}\". STDOUT: {stdout}"
);
Ok(())
}
#[tokio::test]
async fn test_logical_and_short_circuit_chain() -> anyhow::Result<()> {
init();
ensure_global_cleanup_registered();
let script_content = r#"
trace calculate_something {
// true && true && false => false
print (1 && 1 && 0);
// true && true && true => true
print (1 && 1 && 1);
}
"#;
let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 5).await?;
assert_eq!(exit_code, 0, "stderr={stderr} stdout={stdout}");
let saw_true = stdout.contains("true");
let saw_false = stdout.contains("false");
assert!(
saw_true,
"Expected at least one true result. STDOUT: {stdout}"
);
assert!(
saw_false,
"Expected at least one false result. STDOUT: {stdout}"
);
Ok(())
}
#[tokio::test]
async fn test_syntax_error() -> anyhow::Result<()> {
init();
ensure_global_cleanup_registered();
let script_content = r#"
trace calculate_something {
print "missing semicolon" // Missing semicolon - should cause parse error
invalid_token_here
}
"#;
println!("=== Syntax Error Test ===");
let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 5).await?;
println!("Exit code: {exit_code}");
println!("STDOUT: {stdout}");
println!("STDERR: {stderr}");
println!("=========================");
// Should fail fast with syntax error
assert_ne!(exit_code, 0, "Invalid syntax should cause non-zero exit");
assert!(
stderr.contains("Parse error") || stderr.contains("not running"),
"Should contain parse error: {stderr}"
);
if stderr.contains("Parse error") {
println!("✓ Syntax error correctly detected and rejected");
} else {
println!(
"○ Ghostscope exited because target process ended before parsing (stderr: {})",
stderr.trim()
);
}
Ok(())
}
#[tokio::test]
async fn test_format_mismatch() -> anyhow::Result<()> {
init();
ensure_global_cleanup_registered();
let script_content = r#"
trace calculate_something {
print "format {} {} but only one arg", a; // Format/argument count mismatch
}
"#;
println!("=== Format Mismatch Test ===");
let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 5).await?;
println!("Exit code: {exit_code}");
println!("STDOUT: {stdout}");
println!("STDERR: {stderr}");
println!("============================");
// Should fail fast with format error
assert_ne!(exit_code, 0, "Format mismatch should cause non-zero exit");
// Check for format validation error
if stderr.contains("Parse error")
|| stderr.contains("Type error")
|| stderr.contains("format")
|| stderr.contains("placeholders")
{
println!("✓ Format mismatch correctly detected");
} else {
println!("⚠️ Expected format validation error, got: {stderr}");
}
Ok(())
}
#[tokio::test]
async fn test_nonexistent_function() -> anyhow::Result<()> {
init();
ensure_global_cleanup_registered();
let script_content = r#"
trace nonexistent_function_12345 {
print "This function does not exist in sample_program";
}
"#;
println!("=== Nonexistent Function Test ===");
let (exit_code, stdout, stderr) = run_ghostscope_with_script(script_content, 5).await?;
println!("Exit code: {exit_code}");
println!("STDOUT: {stdout}");
println!("STDERR: {stderr}");
println!("=================================");
// Should fail fast when function doesn't exist
assert_ne!(
exit_code, 0,
"Nonexistent function should cause non-zero exit"
);
assert!(
!stderr.contains("Parse error"),
"Script syntax should be valid: {stderr}"
);
if stderr.contains("No uprobe configurations created") {
println!("✓ Correctly detected that target function doesn't exist");
} else {
println!("⚠️ Expected 'No uprobe configurations' error, got: {stderr}");
}
Ok(())
}
#[tokio::test]
async fn test_function_level_tracing() -> anyhow::Result<()> {
init();
ensure_global_cleanup_registered();
let script_content = r#"
trace calculate_something {
print "CALC: a={} b={}", a, b;
}
"#;
// Test with both optimization levels.
// TODO: Re-enable optimized runs once we can reconstruct inlined symbols without full debug info.
let optimization_levels = [OptimizationLevel::Debug, OptimizationLevel::O2];
for opt_level in &optimization_levels {
println!(
"=== Function Level Tracing Test ({}) ===",
opt_level.description()
);
if *opt_level != OptimizationLevel::Debug {
println!(
"⏭️ Skipping {} run (TODO: handle inlined symbols without full debug info)",
opt_level.description()
);
continue;
}
let (exit_code, stdout, stderr) =
run_ghostscope_with_script_opt(script_content, 3, *opt_level).await?;
println!("Exit code: {exit_code}");
println!("STDOUT: {stdout}");
println!("STDERR: {stderr}");
println!("===============================================");
// If we have permissions, should run successfully and produce output
assert_eq!(
exit_code,
0,
"Ghostscope should succeed for {} (stderr: {})",
opt_level.description(),
stderr
);
println!("✓ Ghostscope attached and ran successfully");
// Parse output to validate math: a == b - 5
let mut math_validations = 0;
let mut function_calls_found = 0;
let mut validation_errors = Vec::new();
for line in stdout.lines() {
if line.contains("CALC: ") {
function_calls_found += 1;
if let Some((a, b)) = parse_calc_line_simple(line) {
if a == b - 5 {
println!("✓ Math validation passed: a={} == b-5={}", a, b - 5);
math_validations += 1;
} else {
let error_msg =
format!("Math validation failed: a={a} != b-5={} (b={b})", b - 5);
println!("❌ {error_msg}");
validation_errors.push(error_msg);
}
} else {
println!("⚠️ Failed to parse line: {line}");
}
}
}
if function_calls_found == 0 {
panic!("❌ No function calls captured - test failed. Expected at least one calculate_something call. This indicates either:\n 1. sample_program is not running\n 2. Function is not being called\n 3. Ghostscope failed to attach properly");
} else if !validation_errors.is_empty() {
panic!("❌ Function calls captured but math validation failed:\n Found {} function calls, {} validation errors:\n {}",
function_calls_found, validation_errors.len(), validation_errors.join("\n "));
} else if math_validations > 0 {
println!("✓ Validated {math_validations} calculate_something calls");
}
println!("===============================================");
}
Ok(())
}
#[tokio::test]
async fn test_multiple_trace_targets() -> anyhow::Result<()> {
init();
ensure_global_cleanup_registered();
// Test both function-level and line-level tracing in one script
let script_content = r#"
trace calculate_something {
print "FUNC: a={} b={}", a, b;
}
trace sample_program.c:16 {
print "LINE16: a={} b={} result={}", a, b, result;
}
"#;
let optimization_levels = [OptimizationLevel::Debug, OptimizationLevel::O2];
for opt_level in &optimization_levels {
println!(
"=== Multiple Trace Targets Test ({}) ===",
opt_level.description()
);
let (exit_code, stdout, stderr) =
run_ghostscope_with_script_opt(script_content, 3, *opt_level).await?;
println!("Exit code: {exit_code}");
println!("STDOUT: {stdout}");