-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcompiler.diff
More file actions
4043 lines (4026 loc) · 198 KB
/
compiler.diff
File metadata and controls
4043 lines (4026 loc) · 198 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
diff -ruN --color rust-1.81.0/compiler/rustc_driver_impl/Cargo.toml deepSURF/code/rust/compiler/rustc_driver_impl/Cargo.toml
--- rust-1.81.0/compiler/rustc_driver_impl/Cargo.toml 2025-11-28 21:37:20.018619739 +0000
+++ deepSURF/code/rust/compiler/rustc_driver_impl/Cargo.toml 2025-11-28 21:00:37.382413054 +0000
@@ -19,6 +19,7 @@
rustc_expand = { path = "../rustc_expand" }
rustc_feature = { path = "../rustc_feature" }
rustc_fluent_macro = { path = "../rustc_fluent_macro" }
+rustc_hir = { path = "../rustc_hir" } #gandrout
rustc_hir_analysis = { path = "../rustc_hir_analysis" }
rustc_hir_pretty = { path = "../rustc_hir_pretty" }
rustc_hir_typeck = { path = "../rustc_hir_typeck" }
@@ -46,7 +47,9 @@
rustc_target = { path = "../rustc_target" }
rustc_trait_selection = { path = "../rustc_trait_selection" }
rustc_ty_utils = { path = "../rustc_ty_utils" }
+rustc_surf = { path = "../rustc_surf" }
serde_json = "1.0.59"
+serde = "*" #gandrout
shlex = "1.0"
time = { version = "0.3.36", default-features = false, features = ["alloc", "formatting", "parsing", "macros"] }
tracing = { version = "0.1.35" }
diff -ruN --color rust-1.81.0/compiler/rustc_driver_impl/src/lib.rs deepSURF/code/rust/compiler/rustc_driver_impl/src/lib.rs
--- rust-1.81.0/compiler/rustc_driver_impl/src/lib.rs 2025-11-28 21:37:20.018619739 +0000
+++ deepSURF/code/rust/compiler/rustc_driver_impl/src/lib.rs 2025-11-28 21:00:37.382413054 +0000
@@ -15,6 +15,12 @@
#![feature(panic_update_hook)]
#![feature(result_flattening)]
#![feature(rustdoc_internals)]
+#![allow(unused_imports)]
+#![feature(box_patterns)]
+#![allow(unused_variables)]
+#![allow(rustc::usage_of_ty_tykind)]
+#![allow(rustc::potential_query_instability)]
+//#![allow(dead_code, rustc::default_hash_types)] //gandrout
// tidy-alphabetical-end
use rustc_ast as ast;
@@ -31,6 +37,7 @@
use rustc_feature::find_gated_cfg;
use rustc_interface::util::{self, get_codegen_backend};
use rustc_interface::{interface, Queries};
+use rustc_lint::builtin::UNSAFE_OP_IN_UNSAFE_FN;
use rustc_lint::unerased_lint_store;
use rustc_metadata::creader::MetadataLoader;
use rustc_metadata::locator;
@@ -47,13 +54,14 @@
use rustc_span::FileName;
use rustc_target::json::ToJson;
use rustc_target::spec::{Target, TargetTriple};
+use std::any::Any;
use std::cmp::max;
-use std::collections::BTreeMap;
+use std::collections::{BTreeMap, HashSet};
use std::env;
use std::ffi::OsString;
use std::fmt::Write as _;
use std::fs::{self, File};
-use std::io::{self, IsTerminal, Read, Write};
+use std::io::{self, IsTerminal, Read, Write, BufWriter};
use std::panic::{self, catch_unwind, PanicHookInfo};
use std::path::PathBuf;
use std::process::{self, Command, Stdio};
@@ -64,6 +72,25 @@
use time::OffsetDateTime;
use tracing::trace;
+//gandrout imports
+use rustc_data_structures::fx::FxHashMap;
+use std::hash::Hash;
+use serde::{Serialize, Deserialize};
+use rustc_hir::{ArrayLen, Safety::*};
+use rustc_hir::OwnerId;
+use rustc_hir::QPath::Resolved;
+use rustc_surf::*;
+use rustc_middle::mir::{self};
+use rustc_middle::ty::{self, Ty, TyKind, TyCtxt};
+use rustc_middle::query;
+use rustc_hir::def_id::DefId;
+use rustc_hir::def::{Res::{Def, PrimTy}, DefKind};
+use rustc_data_structures::fx::FxHashSet;
+use rustc_middle::mir::ConstValue;
+use rustc_session::config::EntryFnType;
+use rustc_middle::mir::interpret::ErrorHandled;
+use rustc_middle::mir::interpret::InvalidProgramInfo::TooGeneric;
+
#[allow(unused_macros)]
macro do_not_use_print($($t:tt)*) {
std::compile_error!(
@@ -182,12 +209,19 @@
}
}
-#[derive(Default)]
-pub struct TimePassesCallbacks {
- time_passes: Option<TimePassesFormat>,
+pub struct SurfCallbacks {
+ time_passes: Option<TimePassesFormat>, // from the vanilla compiler
}
-impl Callbacks for TimePassesCallbacks {
+impl SurfCallbacks{
+ fn new() -> SurfCallbacks{
+ Self {
+ time_passes: Default::default(),
+ }
+ }
+}
+
+impl Callbacks for SurfCallbacks {
// JUSTIFICATION: the session doesn't exist at this point.
#[allow(rustc::bad_opt_access)]
fn config(&mut self, config: &mut interface::Config) {
@@ -196,10 +230,218 @@
//
self.time_passes = (config.opts.prints.is_empty() && config.opts.unstable_opts.time_passes)
.then(|| config.opts.unstable_opts.time_passes_format);
- config.opts.trimmed_def_paths = true;
+ config.opts.trimmed_def_paths = false;
+ }
+
+ fn after_analysis<'tcx>(&mut self, _compiler: &interface::Compiler, queries: &'tcx Queries<'tcx>) -> Compilation {
+ if let Ok(_) = env::var("SURF_ANALYZE_LIB"){
+ if let Some(targeting_crate_name) = &*TARGET_CRATE_NAME{
+ queries.global_ctxt().unwrap().enter(|tcx| {
+ let current_crate_name = tcx.crate_name(LOCAL_CRATE).to_ident_string();
+ if current_crate_name == *targeting_crate_name {
+ //safe_println!("Effective Visibilities Set: {:#?}", tcx.effective_visibilities(()));
+
+ // Record Crate's Dependencies
+ let crate_deps = tcx.postorder_cnums(());
+ let mut crate_deps_names = Vec::<String>::new();
+ for dep in crate_deps{
+ crate_deps_names.push(tcx.crate_name(*dep).to_ident_string());
+ }
+ *TARGET_CRATE_DEPS.lock().unwrap() = crate_deps_names.into_iter().collect();
+ // Get the unique id of the crate
+ let crate_id = tcx.stable_crate_id(LOCAL_CRATE).as_u64();
+
+ let reachable_set = tcx.reachable_set(());
+ //safe_println!("Reachable Set: {:#?}", reachable_set);
+ //safe_println!("Reachable Non Generics Set: {:#?}", tcx.reachable_non_generics(LOCAL_CRATE));
+ //safe_println!("Exported Symbols Set: {:#?}", tcx.exported_symbols(LOCAL_CRATE));
+ let test_traits = tcx.traits(LOCAL_CRATE);
+ let trait_impls = tcx.trait_impls_in_crate(LOCAL_CRATE);
+ for trait_impl_def_id in trait_impls{
+ tcx.impl_item_implementor_ids(trait_impl_def_id)
+ .items()
+ .all(|(def_id, impl_id)|{
+ SURF_TRAIT_DEF_TO_IMPL.lock()
+ .unwrap()
+ .entry(*def_id)
+ .or_insert(FxHashSet::<DefId>::default())
+ .insert(*impl_id);
+ true
+ });
+ }
+ // Record HIR Items (Fns, Methods)
+ for item_id in tcx.hir().items() {
+ let hir = tcx.hir();
+ let item = hir.item(item_id);
+ let owner_id = item_id.owner_id;
+ let def_id = item_id.owner_id.to_def_id();
+ match item.kind{
+ rustc_hir::ItemKind::Fn(fn_sign, _, _) => {
+ let fn_name = ty::print::with_no_trimmed_paths!(tcx.def_path_str(owner_id));
+ let fn_safety = if surf_fn_has_unsafe_block(def_id){
+ SurfFnSafety::UnsafeBlockFn
+ }else{
+ match fn_sign.header.safety{
+ Unsafe => SurfFnSafety::UnsafeFn,
+ Safe => SurfFnSafety::SafeFn,
+ }
+ };
+ let visibility = match tcx.effective_visibilities(()).is_exported(owner_id.def_id){
+ true => SurfFnVisibility::PubFn,
+ false => SurfFnVisibility::PrvFn,
+ };
+ surf_add_fn(def_id, &fn_name,
+ fn_safety, ¤t_crate_name, visibility,
+ SurfFnType::Fn);
+ },
+ rustc_hir::ItemKind::Impl(impl_body) => {
+ let mut trait_ref_def_id = None;
+ if let Some(trait_ref) = impl_body.of_trait{
+ if let Def(DefKind::Trait, trait_def_id) = trait_ref.path.res{
+ trait_ref_def_id = Some(trait_def_id);
+ }
+ }
+ for impl_item in impl_body.items{
+ let impl_name = ty::print::with_no_trimmed_paths!(tcx.def_path_str(owner_id));
+ let impl_item_owner_id = impl_item.id.owner_id;
+ let impl_item_def_id = impl_item_owner_id.to_def_id();
+ match tcx.hir().expect_impl_item(impl_item_owner_id.def_id).kind{
+ rustc_hir::ImplItemKind::Fn(fn_sign, _) => {
+ let method_name = ty::print::with_no_trimmed_paths!(tcx.def_path_str(impl_item_owner_id));
+ let method_safety = if surf_fn_has_unsafe_block(impl_item_def_id){
+ SurfFnSafety::UnsafeBlockFn
+ }else{
+ match fn_sign.header.safety{
+ Unsafe => SurfFnSafety::UnsafeFn,
+ Safe => SurfFnSafety::SafeFn,
+ }
+ };
+ let visibility = match tcx.effective_visibilities(()).is_exported(impl_item_owner_id.def_id){
+ true => SurfFnVisibility::PubFn,
+ false => SurfFnVisibility::PrvFn,
+ };
+ surf_add_fn(impl_item_def_id, &method_name,
+ method_safety, ¤t_crate_name, visibility,
+ SurfFnType::Method(SurfTrait::new(&impl_name, trait_ref_def_id)));
+ },
+ _ => (),
+ }
+ }
+ },
+ _ => {},
+ }
+ }
+ // Iterate through the HIR items
+ // Record the callers
+ for item_id in tcx.hir().items() {
+ let hir = tcx.hir();
+ let item = hir.item(item_id);
+ let owner_id = item_id.owner_id;
+ let def_id = item_id.owner_id.to_def_id();
+ match item.kind {
+ // Get the list of the functions
+ rustc_hir::ItemKind::Fn(fn_sign, _, _) => {
+ surf_record_calls(tcx, def_id);
+ }
+ // Get the list of the methods
+ rustc_hir::ItemKind::Impl(impl_body) => {
+ if let Some(trait_ref) = impl_body.of_trait{
+ if let Def(DefKind::Trait, trait_def_id) = trait_ref.path.res{
+ let trait_ref_def_id = Some(trait_def_id);
+ match impl_body.self_ty.kind{
+ rustc_hir::TyKind::Path(Resolved(_, resolved_path)) => {
+ match resolved_path.res{
+ Def(DefKind::Struct | DefKind::Enum, cmplx_ty_def_id) => {
+ if !surf_is_vec(tcx, cmplx_ty_def_id)
+ && !tcx.adt_def(cmplx_ty_def_id).is_box()
+ && !surf_is_maybeuinit(tcx, cmplx_ty_def_id)
+ && !surf_is_option(tcx, cmplx_ty_def_id)
+ && !surf_is_result(tcx, cmplx_ty_def_id)
+ && !surf_is_string(tcx, cmplx_ty_def_id){
+ SURF_TRAITS_TO_CMPLX.lock().unwrap()
+ .entry(trait_def_id)
+ .or_insert(FxHashSet::<DefId>::default())
+ .insert(cmplx_ty_def_id);
+ if surf_is_iter_trait(tcx, trait_def_id){
+ SURF_CONSUMABLE_CMPLX.lock().unwrap().insert(cmplx_ty_def_id);
+ }
+ }
+ },
+ PrimTy(prim_hir_ty) => {
+ SURF_TRAITS_TO_PRIM.lock().unwrap()
+ .entry(trait_def_id)
+ .or_insert(FxHashSet::<rustc_hir::PrimTy>::default())
+ .insert(prim_hir_ty);
+ },
+ _ => {},
+ }
+ },
+ _ => {},
+ }
+ }
+ }
+ for impl_item in impl_body.items{
+ let impl_item_owner_id = impl_item.id.owner_id;
+ let impl_item_def_id = impl_item_owner_id.to_def_id();
+ match tcx.hir().expect_impl_item(impl_item_owner_id.def_id).kind{
+ rustc_hir::ImplItemKind::Fn(fn_sign, _) => {
+ surf_record_calls(tcx, impl_item_def_id);
+ },
+ _ => (),
+ }
+ }
+ }
+ _ => (),
+ }
+ }
+ surf_cfg_analysis(tcx);
+ surf_unsafe_reaching_apis_analysis(tcx);
+ surf_update_self_flag(tcx);
+ surf_update_drop_flag(tcx);
+ surf_update_display_flag(tcx);
+ surf_update_debug_flag(tcx);
+ surf_record_macro_expanded_urapis(tcx);
+ //surf_export_cfg_to_dot(&crate_name, crate_id);
+ load_target_toml_data();
+ surf_write_func_dict(¤t_crate_name, crate_id);
+ surf_write_macro_exp_urapis(¤t_crate_name, crate_id);
+ surf_write_used_deps(¤t_crate_name, crate_id);
+ surf_write_urapi_dict(¤t_crate_name, crate_id);
+ surf_write_urapi_dict_llm(¤t_crate_name, crate_id);
+ surf_write_complex_types_dict(¤t_crate_name, crate_id);
+ surf_write_constructors_dict(¤t_crate_name, crate_id);
+ surf_write_constructors_dict_llm(¤t_crate_name, crate_id);
+ surf_write_enums_dict(¤t_crate_name, crate_id);
+ surf_write_trait_fns_dict(¤t_crate_name, crate_id);
+ surf_write_traits_dict(¤t_crate_name, crate_id);
+ surf_compute_stats();
+ surf_write_stats(¤t_crate_name, crate_id);
+ //safe_println!("{:#?}", MACRO_EXP_URAPIS.lock().unwrap().clone())
+ }
+ });
+ }
+ }
+ else if let Ok(_) = env::var("SURF_RECORD_URAPIS"){
+ if let Some(targeting_crate_name) = &*TARGET_CRATE_NAME{
+ queries.global_ctxt().unwrap().enter(|tcx| {
+ let current_crate_name = tcx.crate_name(LOCAL_CRATE).to_ident_string();
+ //safe_println!("Crate: {:?}", current_crate_name);
+ if current_crate_name == *targeting_crate_name {
+ //safe_println!("BIN: {:?} -- {:?}", current_crate_name, tcx.entry_fn(()));
+ if let Some((main_def_id, EntryFnType::Main { .. })) = tcx.entry_fn(()){
+ if let Some(fuzz_closure_def_id) = surf_get_fuzz_closure_def_id(tcx, main_def_id){
+ surf_print_called_urapis(surf_get_called_urapis(tcx, fuzz_closure_def_id));
+ }
+ }
+ }
+ });
+ }
+ }
+ Compilation::Continue
}
}
+
pub fn diagnostics_registry() -> Registry {
Registry::new(rustc_errors::codes::DIAGNOSTICS)
}
@@ -351,7 +593,7 @@
interface::run_compiler(config, |compiler| {
let sess = &compiler.sess;
let codegen_backend = &*compiler.codegen_backend;
-
+
// This is used for early exits unrelated to errors. E.g. when just
// printing some information without compiling, or exiting immediately
// after parsing, etc.
@@ -386,7 +628,7 @@
process_rlink(sess, compiler);
return early_exit();
}
-
+
let linker = compiler.enter(|queries| {
let early_exit = || early_exit().map(|_| None);
queries.parse()?;
@@ -458,7 +700,6 @@
sess.code_stats.print_vtable_sizes(crate_name);
}
-
Ok(Some(linker))
})?;
@@ -476,7 +717,7 @@
sess.print_fuel.load(Ordering::SeqCst)
);
}
-
+
Ok(())
})
}
@@ -1562,10 +1803,9 @@
init_rustc_env_logger(&early_dcx);
signal_handler::install();
- let mut callbacks = TimePassesCallbacks::default();
+ let mut callbacks = SurfCallbacks::new();
let using_internal_features = install_ice_hook(DEFAULT_BUG_REPORT_URL, |_| ());
install_ctrlc_handler();
-
let exit_code = catch_with_exit_code(|| {
RunCompiler::new(&args::raw_args(&early_dcx)?, &mut callbacks)
.set_using_internal_features(using_internal_features)
@@ -1578,4 +1818,4 @@
}
process::exit(exit_code)
-}
+}
\ No newline at end of file
diff -ruN --color rust-1.81.0/compiler/rustc_middle/src/ty/context.rs deepSURF/code/rust/compiler/rustc_middle/src/ty/context.rs
--- rust-1.81.0/compiler/rustc_middle/src/ty/context.rs 2025-11-28 21:37:20.106617032 +0000
+++ deepSURF/code/rust/compiler/rustc_middle/src/ty/context.rs 2025-11-28 21:00:37.450410963 +0000
@@ -2469,7 +2469,7 @@
/// does not compute the full elaborated super-predicates but just the set of def-ids. It is used
/// to identify which traits may define a given associated type to help avoid cycle errors.
/// Returns a `DefId` iterator.
- fn super_traits_of(self, trait_def_id: DefId) -> impl Iterator<Item = DefId> + 'tcx {
+ pub fn super_traits_of(self, trait_def_id: DefId) -> impl Iterator<Item = DefId> + 'tcx {
let mut set = FxHashSet::default();
let mut stack = vec![trait_def_id];
diff -ruN --color rust-1.81.0/compiler/rustc_middle/src/ty/sty.rs deepSURF/code/rust/compiler/rustc_middle/src/ty/sty.rs
--- rust-1.81.0/compiler/rustc_middle/src/ty/sty.rs 2025-11-28 21:37:20.114616786 +0000
+++ deepSURF/code/rust/compiler/rustc_middle/src/ty/sty.rs 2025-11-28 21:00:37.454410840 +0000
@@ -980,6 +980,11 @@
}
#[inline]
+ pub fn is_surf_collection(self) -> bool {
+ self.kind().is_surf_collection()
+ }
+
+ #[inline]
pub fn is_adt(self) -> bool {
matches!(self.kind(), Adt(..))
}
diff -ruN --color rust-1.81.0/compiler/rustc_mir_build/Cargo.toml deepSURF/code/rust/compiler/rustc_mir_build/Cargo.toml
--- rust-1.81.0/compiler/rustc_mir_build/Cargo.toml 2025-11-28 21:37:20.118616663 +0000
+++ deepSURF/code/rust/compiler/rustc_mir_build/Cargo.toml 2025-11-28 21:00:37.454410840 +0000
@@ -23,5 +23,6 @@
rustc_span = { path = "../rustc_span" }
rustc_target = { path = "../rustc_target" }
rustc_trait_selection = { path = "../rustc_trait_selection" }
+rustc_surf = { path = "../rustc_surf" }
tracing = "0.1"
# tidy-alphabetical-end
diff -ruN --color rust-1.81.0/compiler/rustc_mir_build/src/check_unsafety.rs deepSURF/code/rust/compiler/rustc_mir_build/src/check_unsafety.rs
--- rust-1.81.0/compiler/rustc_mir_build/src/check_unsafety.rs 2025-11-28 21:37:20.122616540 +0000
+++ deepSURF/code/rust/compiler/rustc_mir_build/src/check_unsafety.rs 2025-11-28 21:00:37.458410717 +0000
@@ -1,3 +1,5 @@
+#![allow(unused_imports)]
+
use crate::build::ExprCategory;
use crate::errors::*;
@@ -15,10 +17,14 @@
use rustc_span::def_id::{DefId, LocalDefId};
use rustc_span::symbol::Symbol;
use rustc_span::{sym, Span};
-
-use std::borrow::Cow;
+use rustc_hir::OwnerId;
+use rustc_surf::*;
+use rustc_span::def_id::LOCAL_CRATE;
+use rustc_data_structures::fx::FxHashMap;
+use std::borrow::{Borrow, BorrowMut, Cow};
use std::mem;
use std::ops::Bound;
+use std::env;
struct UnsafetyVisitor<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
@@ -270,6 +276,14 @@
},
|this| visit::walk_block(this, block),
);
+ if let Ok(_) = env::var("SURF_ANALYZE_LIB"){
+ if let Some(targeting_crate_name) = &*TARGET_CRATE_NAME{
+ let crate_name = self.tcx.crate_name(LOCAL_CRATE).to_ident_string();
+ if crate_name == *targeting_crate_name {
+ surf_add_unsafe_block_fn(hir_id.owner.to_def_id());
+ }
+ }
+ }
}
BlockSafety::Safe => {
visit::walk_block(self, block);
diff -ruN --color rust-1.81.0/compiler/rustc_span/Cargo.toml deepSURF/code/rust/compiler/rustc_span/Cargo.toml
--- rust-1.81.0/compiler/rustc_span/Cargo.toml 2025-11-28 21:37:20.174614940 +0000
+++ deepSURF/code/rust/compiler/rustc_span/Cargo.toml 2025-11-28 21:00:37.494409611 +0000
@@ -18,4 +18,5 @@
sha2 = "0.10.1"
tracing = "0.1"
unicode-width = "0.1.4"
+serde = "*" #gandrout
# tidy-alphabetical-end
diff -ruN --color rust-1.81.0/compiler/rustc_span/src/def_id.rs deepSURF/code/rust/compiler/rustc_span/src/def_id.rs
--- rust-1.81.0/compiler/rustc_span/src/def_id.rs 2025-11-28 21:37:20.174614940 +0000
+++ deepSURF/code/rust/compiler/rustc_span/src/def_id.rs 2025-11-28 21:00:37.494409611 +0000
@@ -10,6 +10,7 @@
use rustc_serialize::{Decodable, Encodable};
use std::fmt;
use std::hash::{BuildHasherDefault, Hash, Hasher};
+use serde::ser::{Serialize, Serializer};
pub type StableCrateIdMap =
indexmap::IndexMap<StableCrateId, CrateNum, BuildHasherDefault<Unhasher>>;
@@ -329,6 +330,16 @@
}
}
+impl Serialize for DefId{
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: Serializer,
+ {
+ let debug_str = format!("{:?}", self);
+ serializer.serialize_str(&debug_str)
+ }
+}
+
rustc_data_structures::define_id_collections!(DefIdMap, DefIdSet, DefIdMapEntry, DefId);
/// A `LocalDefId` is equivalent to a `DefId` with `krate == LOCAL_CRATE`. Since
diff -ruN --color rust-1.81.0/compiler/rustc_surf/Cargo.toml deepSURF/code/rust/compiler/rustc_surf/Cargo.toml
--- rust-1.81.0/compiler/rustc_surf/Cargo.toml 1970-01-01 00:00:00.000000000 +0000
+++ deepSURF/code/rust/compiler/rustc_surf/Cargo.toml 2025-11-28 21:00:37.498409488 +0000
@@ -0,0 +1,18 @@
+[package]
+name = "rustc_surf"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+serde = { version = "1.0", features = ["derive"] }
+serde_derive = "1.0"
+serde_json = "1.0.59"
+
+lazy_static = "*"
+petgraph = "*"
+rustc_data_structures = { path = "../rustc_data_structures" }
+rustc_hir = { path = "../rustc_hir" }
+rustc_span = { path = "../rustc_span" }
+rustc_middle = { path = "../rustc_middle" }
+toml = "*"
+regex = "*"
diff -ruN --color rust-1.81.0/compiler/rustc_surf/src/lib.rs deepSURF/code/rust/compiler/rustc_surf/src/lib.rs
--- rust-1.81.0/compiler/rustc_surf/src/lib.rs 1970-01-01 00:00:00.000000000 +0000
+++ deepSURF/code/rust/compiler/rustc_surf/src/lib.rs 2025-11-28 21:00:37.498409488 +0000
@@ -0,0 +1,3501 @@
+#![allow(rustc::potential_query_instability)]
+use rustc_data_structures::fx::{FxHashMap, FxHashSet};
+use lazy_static::lazy_static;
+use rustc_hir::def::DefKind;
+use rustc_hir::def_id::{DefId, LOCAL_CRATE};
+use rustc_hir::PrimTy;
+use rustc_hir::{ItemKind, Node, Safety, LangItem};
+use rustc_middle::query::Key;
+use rustc_middle::ty::DynKind::Dyn;
+use std::sync::Mutex;
+use serde::Serialize;
+use rustc_middle::ty::{self, AliasTy, AssocItem, AliasTyKind, AssocKind, ClauseKind, ExistentialPredicate, Instance, InstanceKind, ParamTy, Ty, TyCtxt, Visibility, GenericParamDefKind, GenericArgKind};
+use rustc_middle::mir::TerminatorKind;
+use petgraph::graph::*;
+use petgraph::dot::{Config, Dot};
+use std::fs::{self, File};
+use std::env;
+use std::path::Path;
+use std::io::{BufWriter, Write};
+use petgraph::visit::Bfs;
+use petgraph::algo::*;
+use rustc_middle::middle::privacy::Level;
+use toml::Value;
+use rustc_span::{symbol::sym, ExpnKind};
+use std::path::PathBuf;
+//use rustc_span::def_id::DefPathHash;
+use regex::Regex;
+const STD_LIB_CRATES: &[&str] = &[
+ "core",
+ "alloc",
+ "std",
+ "test",
+ "term",
+ "unwind",
+ "proc_macro",
+ "panic_abort",
+ "panic_unwind",
+ "profiler_builtins",
+ "rtstartup",
+ "rustc-std-workspace-core",
+ "rustc-std-workspace-alloc",
+ "rustc-std-workspace-std",
+ "backtrace",
+ ];
+
+lazy_static! {
+ #[derive(Debug)]
+ pub static ref SURF_FNS: Mutex<FxHashMap<DefId, SurfFunction>> = Mutex::new(FxHashMap::default());
+
+ #[derive(Debug)]
+ pub static ref SURF_TRAITS_TO_CMPLX: Mutex<FxHashMap<DefId, FxHashSet<DefId>>> = Mutex::new(FxHashMap::default());
+ pub static ref SURF_CONSUMABLE_CMPLX: Mutex<FxHashSet<DefId>> = Mutex::new(FxHashSet::default());
+ pub static ref SURF_TRAITS_TO_PRIM: Mutex<FxHashMap<DefId, FxHashSet<PrimTy>>> = Mutex::new(FxHashMap::default());
+ pub static ref SURF_UNSAFE_BLOCK_FNS: Mutex<FxHashSet<DefId>> = Mutex::new(FxHashSet::default());
+ pub static ref SURF_TRAIT_DEF_TO_IMPL: Mutex<FxHashMap<DefId, FxHashSet<DefId>>> = Mutex::new(FxHashMap::<DefId, FxHashSet<DefId>>::default());
+ pub static ref SURF_CFG: Mutex<Graph<DefId, ()>> = Mutex::new(Graph::<DefId, ()>::new()); // If you don't need it globally remove it
+ pub static ref SURF_FNS_STATS: Mutex<FxHashMap<&'static str, FxHashMap<&'static str, u64>>> = Mutex::new(FxHashMap::<&'static str, FxHashMap::<&'static str, u64>>::default());
+ pub static ref SURF_APIS_REACH_UNSAFE: Mutex<FxHashMap<DefId, SurfURAPI>> = Mutex::new(FxHashMap::default());
+
+ // Analyzed Complex type Constructors
+ pub static ref SURF_COMPLEX_TYPES_TO_CONSTRUCTORS: Mutex<FxHashMap<DefId, FxHashSet<DefId>>> = Mutex::new(FxHashMap::<DefId, FxHashSet<DefId>>::default());
+ pub static ref SURF_COMPLEX_PENDING_ANALYSIS: Mutex<FxHashSet<DefId>> = Mutex::new(FxHashSet::<DefId>::default());
+
+ pub static ref SURF_CONSTRUCTORS: Mutex<FxHashMap<DefId, SurfConstructorData>> = Mutex::new(FxHashMap::<DefId, SurfConstructorData>::default());
+ pub static ref SURF_TRAIT_FNS: Mutex<FxHashMap<DefId, SurfTraitFnData>> = Mutex::new(FxHashMap::<DefId, SurfTraitFnData>::default());
+ pub static ref SURF_TRAITS: Mutex<FxHashMap<DefId, SurfTraitData>> = Mutex::new(FxHashMap::<DefId, SurfTraitData>::default());
+ pub static ref SURF_ENUMS: Mutex<FxHashMap<DefId, FxHashMap::<String, Vec<SurfFnArg>>>> = Mutex::new(FxHashMap::<DefId, FxHashMap::<String, Vec<SurfFnArg>>>::default());
+
+ // CFG helper data structures
+ pub static ref DEF_ID_TO_NODE: Mutex<FxHashMap<DefId, NodeIndex>> = Mutex::new(FxHashMap::<DefId, NodeIndex>::default());
+ pub static ref NODE_TO_DEF_ID: Mutex<FxHashMap<NodeIndex, DefId>> = Mutex::new(FxHashMap::<NodeIndex, DefId>::default());
+
+ pub static ref TARGET_CRATE_NAME: Option<String> = load_target_crate_name();
+ pub static ref TARGET_CRATE_USED_DEPS: Mutex<FxHashMap<String, CrateDepType>> = Mutex::new(FxHashMap::default());
+ pub static ref TARGET_CRATE_DEPS: Mutex<FxHashSet<String>> = Mutex::new(FxHashSet::default());
+
+ // Macros Recording
+ pub static ref SURF_MACRO_URAPIS: Mutex<FxHashMap<String, FxHashSet<DefId>>> = Mutex::new(FxHashMap::<String, FxHashSet<DefId>>::default());
+
+}
+
+/*
+------------------------------------------------------------------------------------------------------------------
+ Functions for loading data from external files
+------------------------------------------------------------------------------------------------------------------
+*/
+
+/*
+ If env var `SURF_WORKING_PATH` is set, try to set TARGET_CRATE_NAME by reading the related Cargo.toml.
+*/
+fn load_target_crate_name() -> Option<String> {
+ match env::var("SURF_WORKING_PATH"){
+ Ok(targeting_crate_path) => {
+ let targeting_toml_path = format!("{targeting_crate_path}/Cargo.toml");
+ if let Ok(toml_contents) = fs::read_to_string(&targeting_toml_path){
+ if let Ok(toml_entries) = toml_contents.parse::<Value>(){
+ match toml_entries.get("package").and_then(|pkg| pkg.get("name")){
+ Some(crate_name) => {
+ match crate_name.as_str(){
+ Some(crate_name_str) => return Some(crate_name_str.replace("-", "_")),
+ None => eprintln!("Unknown crate name."),
+ }
+ },
+ None => eprintln!("Crate name not found."),
+ }
+ }
+ }
+ },
+ _ => eprintln!("The env variable 'SURF_WORKING_PATH' is not set!"),
+ }
+ None
+}
+
+/*
+ If env var `SURF_WORKING_PATH` is set, try to find the versions of the dependencies
+ used by the targeting crate (TARGET_CRATE_USED_DEPS).
+ We open and read the related Cargo.toml to get the versions of the dependencies.
+*/
+pub fn load_target_toml_data(){
+ if let Ok(targeting_crate_path) = env::var("SURF_WORKING_PATH"){
+ let targeting_toml_path = format!("{targeting_crate_path}/Cargo.toml");
+ if let Ok(toml_contents) = fs::read_to_string(&targeting_toml_path){
+ if let Ok(toml_entries) = toml_contents.parse::<Value>(){
+ if let Some(dependencies) = toml_entries.get("dependencies"){
+ for (key, val) in dependencies.as_table().unwrap() {
+ if let Some(dep_type) = TARGET_CRATE_USED_DEPS.lock().unwrap().get_mut(key){
+ if let Some(version) = val.as_str() {
+ *dep_type = CrateDepType::Version(version.to_string());
+ } else if let Some(table) = val.as_table() {
+ if let Some(path) = table.get("path") {
+ *dep_type = CrateDepType::Path(path.to_string());
+ }
+ else if let Some(version) = table.get("version") {
+ *dep_type = CrateDepType::Version(version.to_string());
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+
+
+/*
+------------------------------------------------------------------------------------------------------------------
+ Functions for checking if an argument is of a specific type or has a specific attribute
+------------------------------------------------------------------------------------------------------------------
+*/
+
+/*
+ Check if the input DefId is the root crate (i.e., has no parent).
+*/
+fn item_is_root_crate<'tcx>(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> bool {
+ tcx.opt_parent(item_def_id).is_some()
+}
+
+/*
+ Check if the the crate where the input DefId is defined either in the dependencies
+ of the current crate or the standard libraries.
+ If is defined inside one of the dependencies, then update the `TARGET_CRATE_USED_DEPS` map.
+*/
+fn item_is_imported<'tcx>(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> bool{
+ let item_crate_name = tcx.crate_name(item_def_id.krate).to_ident_string();
+ if TARGET_CRATE_DEPS.lock().unwrap().contains(&item_crate_name){
+ if !STD_LIB_CRATES.contains(&item_crate_name.as_str()){
+ TARGET_CRATE_USED_DEPS.lock().unwrap().insert(item_crate_name.to_string(), CrateDepType::Empty);
+ }
+ return true;
+ }
+ return false;
+}
+
+/*
+ Check if the input item is publicly accessible from the users of the crate.
+*/
+fn item_is_exported<'tcx>(tcx: TyCtxt<'tcx>, item_def_id: DefId) -> bool{
+ match item_def_id.as_local(){
+ Some(local_def_id) => tcx.effective_visibilities(()).is_exported(local_def_id),
+ _ => false,
+ }
+}
+
+/*
+ Check if the associate input item is Fn kind.
+*/
+fn assoc_item_is_fn(item: &AssocItem) -> bool {
+ item.kind == AssocKind::Fn
+}
+
+/*
+ Check if the associate input item is Type kind.
+*/
+fn assoc_item_is_type(item: &AssocItem) -> bool {
+ item.kind == AssocKind::Type
+}
+
+/*
+ Check if the associate input item is Fn kind and safe.
+*/
+fn assoc_item_is_safe_fn<'tcx>(tcx: TyCtxt<'tcx>, item: &AssocItem) -> bool {
+ assoc_item_is_fn(item) && tcx.fn_sig(item.def_id).skip_binder().skip_binder().safety == Safety::Safe
+}
+
+/*
+ Check if the input surf function is unsafe.
+*/
+fn surf_fn_is_unsafe(surf_fn: &SurfFunction) -> bool {
+ surf_fn.safety == SurfFnSafety::UnsafeFn
+}
+
+/*
+ Check if the input function item has self argument.
+*/
+fn fn_item_has_self<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool{
+ let parent_def_id = tcx.parent(def_id);
+ match tcx.def_kind(parent_def_id){
+ DefKind::Trait
+ | DefKind::Enum
+ | DefKind::Struct
+ | DefKind::Impl { .. } => {
+ let associated_item = tcx.associated_item(def_id);
+ match assoc_item_is_fn(&associated_item){
+ true => associated_item.fn_has_self_parameter,
+ false => false,
+ }
+ },
+ _ => false,
+ }
+}
+
+/*
+ Check if the input function item has default implementation.
+*/
+fn fn_item_has_default_impl<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool{
+ let defaultness = tcx.defaultness(def_id);
+ match defaultness.is_default(){
+ true => defaultness.has_value(),
+ _ => false,
+ }
+}
+
+pub fn surf_has_output<'tcx>(output: Ty<'tcx>) -> bool{
+ match output.kind() {
+ ty::Tuple(list) => !list.is_empty(),
+ _ => true,
+ }
+}
+
+pub fn surf_record_macro_expanded_urapis<'tcx>(tcx: TyCtxt<'tcx>) {
+ let mut macro_exp_urapis_lock = SURF_MACRO_URAPIS.lock().unwrap();
+ for urapi_def_id in SURF_APIS_REACH_UNSAFE.lock().unwrap().keys(){
+ let span = tcx.def_span(urapi_def_id);
+ let expn_data = span.ctxt().outer_expn_data();
+ if let ExpnKind::Macro(_, _) = expn_data.kind{
+ if let Some(_) = expn_data.macro_def_id {
+ macro_exp_urapis_lock.entry(get_stable_def_id_location(tcx, *urapi_def_id)).or_insert(FxHashSet::<DefId>::default()).insert(*urapi_def_id);
+ }
+ }
+
+ }
+}
+
+pub fn surf_fn_has_unsafe_block(def_id: DefId) -> bool{
+ SURF_UNSAFE_BLOCK_FNS.lock().unwrap().contains(&def_id)
+}
+
+pub fn surf_has_unresolved_calls(surf_urapi: &SurfURAPI, trait_def_id: DefId, fn_def_id: DefId) -> bool{
+ match surf_urapi.reachable_unresolved_callees.get(&trait_def_id){
+ Some(unresolved_fns) => unresolved_fns.contains(&fn_def_id),
+ None => false,
+ }
+}
+
+pub fn surf_fn_calls_unresolved(surf_func: &SurfFunction) -> bool{
+ !surf_func.unresolved_callees.is_empty()
+}
+
+pub fn surf_is_directly_public<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool{
+ //println!("DEF: {:?}", def_id);
+ let local_def_id = def_id.as_local().unwrap();
+ return tcx.effective_visibilities(()).is_directly_public(local_def_id)
+}
+
+pub fn surf_add_fn(
+ def_id: DefId,
+ func_name: &str,
+ safety: SurfFnSafety,
+ crate_name: &str,
+ visibility: SurfFnVisibility,
+ fn_type: SurfFnType
+){
+ SURF_FNS.lock().unwrap()
+ .insert(def_id, SurfFunction::new(func_name, safety, crate_name, visibility, fn_type));
+}
+
+pub fn surf_add_unsafe_block_fn(def_id: DefId){
+ SURF_UNSAFE_BLOCK_FNS.lock().unwrap().insert(def_id);
+}
+
+pub fn surf_add_caller(callee_def_id: DefId, caller_def_id: DefId){
+ //println!("HERE!: {:?} -> {:?}", caller_def_id, callee_def_id);
+ if let Some(callee_surf_func) = SURF_FNS.lock().unwrap().get_mut(&callee_def_id){
+ //println!("INSIDE!");
+ callee_surf_func.callers.insert(caller_def_id);
+ }
+}
+
+pub fn surf_add_unresolved_callee(caller_def_id: DefId, callee_def_id: DefId){
+ if let Some(caller_surf_func) = SURF_FNS.lock().unwrap().get_mut(&caller_def_id){
+ caller_surf_func.unresolved_callees.insert(callee_def_id);
+ }
+}
+
+pub fn surf_get_fuzz_closure_def_id<'tcx>(tcx: TyCtxt<'tcx>, main_def_id: DefId) -> Option<DefId>{
+ if tcx.is_mir_available(main_def_id){
+ let main_body = tcx.optimized_mir(main_def_id);
+ let main_local_def_id = main_body.source.def_id().expect_local();
+ if !tcx.hir().body_owner_kind(main_local_def_id).is_fn_or_closure(){
+ return None;
+ }
+ let param_env = tcx.param_env_reveal_all_normalized(main_local_def_id);
+ let blocks = main_body.basic_blocks.iter();
+ for bb_data in blocks{
+ let terminator = bb_data.terminator();
+ if let TerminatorKind::Call { ref func, .. } = terminator.kind {
+ let func_type = func.ty(main_body, tcx);
+ if let ty::FnDef(callee_def_id, args) = *func_type.kind(){
+ let args = tcx.try_normalize_erasing_regions(param_env, args).ok().unwrap();
+ if let Some(callee) = Instance::resolve(tcx, param_env, callee_def_id, args).ok().flatten(){
+ if let InstanceKind::Item(callee_impl_def_id) = callee.def{
+ if let Some(item_name) = tcx.opt_item_name(callee_impl_def_id){
+ if item_name.to_ident_string() == "fuzz" && tcx.crate_name(callee_impl_def_id.krate).to_ident_string() == "afl"{
+ if let ty::GenericArgKind::Type(arg_ty) = args[0].unpack(){
+ if let ty::Closure(fuzz_closure_def_id, _) = arg_ty.kind(){
+ return Some(*fuzz_closure_def_id)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ None
+}
+
+pub fn surf_get_called_urapis<'tcx>(tcx: TyCtxt<'tcx>, fuzz_closure_def_id: DefId) -> FxHashSet<String>{
+ let mut called_urapis = FxHashSet::<String>::default();
+ if tcx.is_mir_available(fuzz_closure_def_id){
+ let fuzz_closure_body = tcx.optimized_mir(fuzz_closure_def_id);
+ let fuzz_closure_local_def_id = fuzz_closure_body.source.def_id().expect_local();
+ if tcx.hir().body_owner_kind(fuzz_closure_local_def_id).is_fn_or_closure(){
+ let param_env = tcx.param_env_reveal_all_normalized(fuzz_closure_local_def_id);
+ let blocks = fuzz_closure_body.basic_blocks.iter();
+ for bb_data in blocks{
+ let terminator = bb_data.terminator();
+ if let TerminatorKind::Call { ref func, .. } = terminator.kind {
+ let func_type = func.ty(fuzz_closure_body, tcx);
+ if let ty::FnDef(callee_def_id, args) = *func_type.kind(){
+ let args = tcx.try_normalize_erasing_regions(param_env, args).ok().unwrap();
+ if let Some(callee) = Instance::resolve(tcx, param_env, callee_def_id, args).ok().flatten(){
+ if let InstanceKind::Item(callee_impl_def_id) = callee.def {
+ called_urapis.insert(get_stable_def_id_location(tcx, callee_impl_def_id));
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ called_urapis
+}
+
+pub fn surf_print_called_urapis(called_urapis: FxHashSet<String>){
+ let json = serde_json::to_string(&called_urapis).unwrap();
+ println!("---BEGIN-CALLED-URAPIS---");
+ println!("{}", json);
+ println!("---END-CALLED-URAPIS---");
+}
+
+///rust/compiler/rustc_mir_transform/src/inline.rs
+pub fn surf_record_calls<'tcx>(tcx: TyCtxt<'tcx>, caller_def_id: DefId) {
+ let caller_body;
+ if tcx.is_mir_available(caller_def_id){
+ caller_body = tcx.optimized_mir(caller_def_id);
+ let caller_local_def_id = caller_body.source.def_id().expect_local();
+ if !tcx.hir().body_owner_kind(caller_local_def_id).is_fn_or_closure(){
+ return;
+ }
+ let param_env = tcx.param_env_reveal_all_normalized(caller_local_def_id);
+ let blocks = caller_body.basic_blocks.iter();
+ for bb_data in blocks{
+ let terminator = bb_data.terminator();
+ if let TerminatorKind::Call { ref func, .. } = terminator.kind {
+ let func_type = func.ty(caller_body, tcx);
+ //println!("FUNC: {:?} -> {:?}", caller_def_id, func_type);
+ match *func_type.kind() {
+ ty::FnDef(callee_def_id, args) => {
+ let args = tcx.try_normalize_erasing_regions(param_env, args).ok().unwrap();
+ match Instance::resolve(tcx, param_env, callee_def_id, args).ok().flatten(){
+ Some(callee) => {
+ match callee.def {
+ // The dyn case
+ InstanceKind::Virtual(gen_fn_def_id, _) => {
+ //println!("1: {:?}", gen_fn_def_id);
+ if let Some(trait_impls) = SURF_TRAIT_DEF_TO_IMPL.lock().unwrap().get(&gen_fn_def_id){
+ for callee_impl_def_id in trait_impls{
+ surf_add_caller(*callee_impl_def_id, caller_def_id);
+ }
+ }
+ surf_add_unresolved_callee(caller_def_id, gen_fn_def_id);
+ },
+ // The normal case
+ InstanceKind::Item(callee_impl_def_id) => {
+ //println!("2: {:?}", callee_impl_def_id);
+ surf_add_caller(callee_impl_def_id, caller_def_id);
+ },
+ // The unexpected case
+ _ => {
+ eprintln!("INVESTIGATION NEED: {:?}.", caller_def_id);
+ },
+ }
+ },
+ None => {
+ //println!("3: {:#?}", SURF_TRAIT_DEF_TO_IMPL.lock().unwrap().get(&callee_def_id));
+ if let Some(trait_impls) = SURF_TRAIT_DEF_TO_IMPL.lock().unwrap().get(&callee_def_id){
+ for callee_impl_def_id in trait_impls{
+ surf_add_caller(*callee_impl_def_id, caller_def_id);
+ }
+ }
+ surf_add_unresolved_callee(caller_def_id, callee_def_id);
+ },
+ }
+ },
+ ty::FnPtr(_) => {
+ eprintln!("UNIMPLEMENTED: Call to FnPtr From: {:?}.", caller_def_id);
+ },
+ _ => {
+ eprintln!("INVESTIGATION NEED: {:?}.", caller_def_id);
+ },
+ }
+ }
+ }
+ }
+}
+
+pub fn surf_cfg_analysis<'tcx>(tcx: TyCtxt<'tcx>){
+ // Construct The Nodes
+ for (func_def_id, _) in SURF_FNS.lock().unwrap().iter(){
+ let node = SURF_CFG.lock().unwrap().add_node(*func_def_id);
+ DEF_ID_TO_NODE.lock().unwrap().entry(*func_def_id).or_insert(node);
+ NODE_TO_DEF_ID.lock().unwrap().entry(node).or_insert(*func_def_id);
+ }
+ // Construct The Edges
+ let def_id_to_node = DEF_ID_TO_NODE.lock().unwrap().clone();
+ let node_to_def_id = NODE_TO_DEF_ID.lock().unwrap().clone();
+ for (callee_def_id, callee_surf_func) in SURF_FNS.lock().unwrap().iter(){
+ for caller_def_id in callee_surf_func.callers.iter(){
+ let caller_node = def_id_to_node.get(caller_def_id).unwrap();
+ let callee_node = def_id_to_node.get(callee_def_id).unwrap();
+ SURF_CFG.lock().unwrap().add_edge(*callee_node, *caller_node, ());
+ }
+ }
+ // Record The Public Predecessors That Reach Unsafe Blocks
+ let mut cfg_copy = SURF_CFG.lock().unwrap().clone();
+ let surf_fns_copy = SURF_FNS.lock().unwrap().clone();
+ for (func_def_id, funch_node) in def_id_to_node.iter(){
+ if let Some(callee_surf_func) = SURF_FNS.lock().unwrap().get_mut(&func_def_id){