1use std::fmt::Write as _;
9
10use rustc_abi::{ExternAbi, Integer};
11use rustc_data_structures::base_n::{ALPHANUMERIC_ONLY, CASE_INSENSITIVE, ToBaseN};
12use rustc_data_structures::fx::FxHashMap;
13use rustc_hir as hir;
14use rustc_hir::attrs::AttributeKind;
15use rustc_hir::find_attr;
16use rustc_middle::bug;
17use rustc_middle::ty::layout::IntegerExt;
18use rustc_middle::ty::{
19 self, Const, ExistentialPredicate, FloatTy, FnSig, GenericArg, GenericArgKind, GenericArgsRef,
20 IntTy, List, Region, RegionKind, TermKind, Ty, TyCtxt, TypeFoldable, UintTy,
21};
22use rustc_span::def_id::DefId;
23use tracing::instrument;
24
25use crate::cfi::typeid::TypeIdOptions;
26use crate::cfi::typeid::itanium_cxx_abi::transform::{TransformTy, TransformTyOptions};
27
28pub(crate) type EncodeTyOptions = TypeIdOptions;
30
31#[derive(Eq, Hash, PartialEq)]
33pub(crate) enum DictKey<'tcx> {
34 Ty(Ty<'tcx>, TyQ),
35 Region(Region<'tcx>),
36 Const(Const<'tcx>),
37 Predicate(ExistentialPredicate<'tcx>),
38}
39
40#[derive(Eq, Hash, PartialEq)]
42pub(crate) enum TyQ {
43 None,
44 Const,
45 Mut,
46}
47
48fn compress<'tcx>(
51 dict: &mut FxHashMap<DictKey<'tcx>, usize>,
52 key: DictKey<'tcx>,
53 comp: &mut String,
54) {
55 match dict.get(&key) {
56 Some(num) => {
57 comp.clear();
58 let _ = write!(comp, "S{}_", to_seq_id(*num));
59 }
60 None => {
61 dict.insert(key, dict.len());
62 }
63 }
64}
65
66fn encode_args<'tcx>(
69 tcx: TyCtxt<'tcx>,
70 args: GenericArgsRef<'tcx>,
71 for_def: DefId,
72 has_erased_self: bool,
73 dict: &mut FxHashMap<DictKey<'tcx>, usize>,
74 options: EncodeTyOptions,
75) -> String {
76 let mut s = String::new();
78 let args: Vec<GenericArg<'_>> = args.iter().collect();
79 if !args.is_empty() {
80 s.push('I');
81 let def_generics = tcx.generics_of(for_def);
82 for (n, arg) in args.iter().enumerate() {
83 match arg.kind() {
84 GenericArgKind::Lifetime(region) => {
85 s.push_str(&encode_region(region, dict));
86 }
87 GenericArgKind::Type(ty) => {
88 s.push_str(&encode_ty(tcx, ty, dict, options));
89 }
90 GenericArgKind::Const(c) => {
91 let n = n + (has_erased_self as usize);
92 let ct_ty =
93 tcx.type_of(def_generics.param_at(n, tcx).def_id).instantiate_identity();
94 s.push_str(&encode_const(tcx, c, ct_ty, dict, options));
95 }
96 }
97 }
98 s.push('E');
99 }
100 s
101}
102
103fn encode_const<'tcx>(
106 tcx: TyCtxt<'tcx>,
107 ct: Const<'tcx>,
108 ct_ty: Ty<'tcx>,
109 dict: &mut FxHashMap<DictKey<'tcx>, usize>,
110 options: EncodeTyOptions,
111) -> String {
112 let mut s = String::from('L');
114
115 match ct.kind() {
116 ty::ConstKind::Param(..) => {
118 s.push_str(&encode_ty(tcx, ct_ty, dict, options));
122 }
123
124 ty::ConstKind::Value(cv) => {
126 s.push_str(&encode_ty(tcx, cv.ty, dict, options));
130
131 match cv.ty.kind() {
135 ty::Int(ity) => {
136 let bits = cv
137 .try_to_bits(tcx, ty::TypingEnv::fully_monomorphized())
138 .expect("expected monomorphic const in cfi");
139 let val = Integer::from_int_ty(&tcx, *ity).size().sign_extend(bits) as i128;
140 if val < 0 {
141 s.push('n');
142 }
143 let _ = write!(s, "{val}");
144 }
145 ty::Uint(_) => {
146 let val = cv
147 .try_to_bits(tcx, ty::TypingEnv::fully_monomorphized())
148 .expect("expected monomorphic const in cfi");
149 let _ = write!(s, "{val}");
150 }
151 ty::Bool => {
152 let val = cv.try_to_bool().expect("expected monomorphic const in cfi");
153 let _ = write!(s, "{val}");
154 }
155 _ => {
156 bug!("encode_const: unexpected type `{:?}`", cv.ty);
157 }
158 }
159 }
160
161 _ => {
162 bug!("encode_const: unexpected kind `{:?}`", ct.kind());
163 }
164 }
165
166 s.push('E');
168
169 compress(dict, DictKey::Const(ct), &mut s);
170
171 s
172}
173
174fn encode_fnsig<'tcx>(
177 tcx: TyCtxt<'tcx>,
178 fn_sig: &FnSig<'tcx>,
179 dict: &mut FxHashMap<DictKey<'tcx>, usize>,
180 options: TypeIdOptions,
181) -> String {
182 let mut s = String::from("F");
184
185 let mut encode_ty_options = EncodeTyOptions::from_bits(options.bits())
186 .unwrap_or_else(|| bug!("encode_fnsig: invalid option(s) `{:?}`", options.bits()));
187 match fn_sig.abi {
188 ExternAbi::C { .. } => {
189 encode_ty_options.insert(EncodeTyOptions::GENERALIZE_REPR_C);
190 }
191 _ => {
192 encode_ty_options.remove(EncodeTyOptions::GENERALIZE_REPR_C);
193 }
194 }
195
196 let transform_ty_options = TransformTyOptions::from_bits(options.bits())
198 .unwrap_or_else(|| bug!("encode_fnsig: invalid option(s) `{:?}`", options.bits()));
199 let mut type_folder = TransformTy::new(tcx, transform_ty_options);
200 let ty = fn_sig.output().fold_with(&mut type_folder);
201 s.push_str(&encode_ty(tcx, ty, dict, encode_ty_options));
202
203 let tys = fn_sig.inputs();
205 if !tys.is_empty() {
206 for ty in tys {
207 let ty = ty.fold_with(&mut type_folder);
208 s.push_str(&encode_ty(tcx, ty, dict, encode_ty_options));
209 }
210
211 if fn_sig.c_variadic {
212 s.push('z');
213 }
214 } else if fn_sig.c_variadic {
215 s.push('z');
216 } else {
217 s.push('v')
220 }
221
222 s.push('E');
224
225 s
226}
227
228fn encode_predicate<'tcx>(
231 tcx: TyCtxt<'tcx>,
232 predicate: ty::PolyExistentialPredicate<'tcx>,
233 dict: &mut FxHashMap<DictKey<'tcx>, usize>,
234 options: EncodeTyOptions,
235) -> String {
236 let mut s = String::new();
239 match predicate.as_ref().skip_binder() {
240 ty::ExistentialPredicate::Trait(trait_ref) => {
241 let name = encode_ty_name(tcx, trait_ref.def_id);
242 let _ = write!(s, "u{}{}", name.len(), name);
243 s.push_str(&encode_args(tcx, trait_ref.args, trait_ref.def_id, true, dict, options));
244 }
245 ty::ExistentialPredicate::Projection(projection) => {
246 let name = encode_ty_name(tcx, projection.def_id);
247 let _ = write!(s, "u{}{}", name.len(), name);
248 s.push_str(&encode_args(tcx, projection.args, projection.def_id, true, dict, options));
249 match projection.term.kind() {
250 TermKind::Ty(ty) => s.push_str(&encode_ty(tcx, ty, dict, options)),
251 TermKind::Const(c) => s.push_str(&encode_const(
252 tcx,
253 c,
254 tcx.type_of(projection.def_id).instantiate(tcx, projection.args),
255 dict,
256 options,
257 )),
258 }
259 }
260 ty::ExistentialPredicate::AutoTrait(def_id) => {
261 let name = encode_ty_name(tcx, *def_id);
262 let _ = write!(s, "u{}{}", name.len(), name);
263 }
264 };
265 compress(dict, DictKey::Predicate(*predicate.as_ref().skip_binder()), &mut s);
266 s
267}
268
269fn encode_predicates<'tcx>(
272 tcx: TyCtxt<'tcx>,
273 predicates: &List<ty::PolyExistentialPredicate<'tcx>>,
274 dict: &mut FxHashMap<DictKey<'tcx>, usize>,
275 options: EncodeTyOptions,
276) -> String {
277 let mut s = String::new();
279 let predicates: Vec<ty::PolyExistentialPredicate<'tcx>> = predicates.iter().collect();
280 for predicate in predicates {
281 s.push_str(&encode_predicate(tcx, predicate, dict, options));
282 }
283 s
284}
285
286fn encode_region<'tcx>(region: Region<'tcx>, dict: &mut FxHashMap<DictKey<'tcx>, usize>) -> String {
288 let mut s = String::new();
290 match region.kind() {
291 RegionKind::ReBound(ty::BoundVarIndexKind::Bound(debruijn), r) => {
292 s.push_str("u6regionI");
293 let num = debruijn.index() as u64;
295 if num > 0 {
296 s.push_str(&to_disambiguator(num));
297 }
298 let _ = write!(s, "{}", r.var.index() as u64);
300 s.push('E');
301 compress(dict, DictKey::Region(region), &mut s);
302 }
303 RegionKind::ReErased => {
304 s.push_str("u6region");
305 compress(dict, DictKey::Region(region), &mut s);
306 }
307 RegionKind::ReBound(ty::BoundVarIndexKind::Canonical, _)
308 | RegionKind::ReEarlyParam(..)
309 | RegionKind::ReLateParam(..)
310 | RegionKind::ReStatic
311 | RegionKind::ReError(_)
312 | RegionKind::ReVar(..)
313 | RegionKind::RePlaceholder(..) => {
314 bug!("encode_region: unexpected `{:?}`", region.kind());
315 }
316 }
317 s
318}
319
320#[instrument(level = "trace", skip(tcx, dict))]
323pub(crate) fn encode_ty<'tcx>(
324 tcx: TyCtxt<'tcx>,
325 ty: Ty<'tcx>,
326 dict: &mut FxHashMap<DictKey<'tcx>, usize>,
327 options: EncodeTyOptions,
328) -> String {
329 let mut typeid = String::new();
330
331 match ty.kind() {
332 ty::Bool => {
340 typeid.push('b');
341 }
342
343 ty::Int(..) | ty::Uint(..) => {
344 let mut s = String::from(match ty.kind() {
346 ty::Int(IntTy::I8) => "u2i8",
347 ty::Int(IntTy::I16) => "u3i16",
348 ty::Int(IntTy::I32) => "u3i32",
349 ty::Int(IntTy::I64) => "u3i64",
350 ty::Int(IntTy::I128) => "u4i128",
351 ty::Int(IntTy::Isize) => "u5isize",
352 ty::Uint(UintTy::U8) => "u2u8",
353 ty::Uint(UintTy::U16) => "u3u16",
354 ty::Uint(UintTy::U32) => "u3u32",
355 ty::Uint(UintTy::U64) => "u3u64",
356 ty::Uint(UintTy::U128) => "u4u128",
357 ty::Uint(UintTy::Usize) => "u5usize",
358 _ => bug!("encode_ty: unexpected `{:?}`", ty.kind()),
359 });
360 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
361 typeid.push_str(&s);
362 }
363
364 ty::Float(float_ty) => {
370 typeid.push_str(match float_ty {
371 FloatTy::F16 => "Dh",
372 FloatTy::F32 => "f",
373 FloatTy::F64 => "d",
374 FloatTy::F128 => "g",
375 });
376 }
377
378 ty::Char => {
379 let mut s = String::from("u4char");
381 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
382 typeid.push_str(&s);
383 }
384
385 ty::Str => {
386 let mut s = String::from("u3str");
388 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
389 typeid.push_str(&s);
390 }
391
392 ty::Never => {
393 let mut s = String::from("u5never");
395 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
396 typeid.push_str(&s);
397 }
398
399 _ if ty.is_unit() => {
402 typeid.push('v');
403 }
404
405 ty::Tuple(tys) => {
407 let mut s = String::from("u5tupleI");
409 for ty in tys.iter() {
410 s.push_str(&encode_ty(tcx, ty, dict, options));
411 }
412 s.push('E');
413 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
414 typeid.push_str(&s);
415 }
416
417 ty::Array(ty0, len) => {
418 let len = len.try_to_target_usize(tcx).expect("expected monomorphic const in cfi");
420 let mut s = String::from("A");
421 let _ = write!(s, "{len}");
422 s.push_str(&encode_ty(tcx, *ty0, dict, options));
423 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
424 typeid.push_str(&s);
425 }
426
427 ty::Pat(ty0, pat) => {
428 let mut s = String::from("u3patI");
430 s.push_str(&encode_ty(tcx, *ty0, dict, options));
431 write!(s, "{:?}", **pat).unwrap();
432 s.push('E');
433 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
434 typeid.push_str(&s);
435 }
436
437 ty::Slice(ty0) => {
438 let mut s = String::from("u5sliceI");
440 s.push_str(&encode_ty(tcx, *ty0, dict, options));
441 s.push('E');
442 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
443 typeid.push_str(&s);
444 }
445
446 ty::Adt(adt_def, args) => {
448 let mut s = String::new();
449 let def_id = adt_def.did();
450 if let Some(encoding) = find_attr!(tcx.get_all_attrs(def_id), AttributeKind::CfiEncoding { encoding } => encoding)
451 {
452 let encoding = encoding.as_str().trim();
453 s.push_str(&encoding);
455 let builtin_types = [
459 "v", "w", "b", "c", "a", "h", "s", "t", "i", "j", "l", "m", "x", "y", "n", "o",
460 "f", "d", "e", "g", "z", "Dh",
461 ];
462 if !builtin_types.contains(&encoding) {
463 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
464 }
465 } else if options.contains(EncodeTyOptions::GENERALIZE_REPR_C) && adt_def.repr().c() {
466 let name = tcx.item_name(def_id).to_string();
480 let _ = write!(s, "{}{}", name.len(), name);
481 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
482 } else {
483 let name = encode_ty_name(tcx, def_id);
486 let _ = write!(s, "u{}{}", name.len(), name);
487 s.push_str(&encode_args(tcx, args, def_id, false, dict, options));
488 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
489 }
490 typeid.push_str(&s);
491 }
492
493 ty::Foreign(def_id) => {
494 let mut s = String::new();
496
497 if let Some(encoding) = find_attr!(tcx.get_all_attrs(*def_id), AttributeKind::CfiEncoding {encoding} => encoding)
498 {
499 s.push_str(encoding.as_str().trim());
501 } else {
502 let name = tcx.item_name(*def_id).to_string();
503 let _ = write!(s, "{}{}", name.len(), name);
504 }
505 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
506 typeid.push_str(&s);
507 }
508
509 ty::FnDef(def_id, args) | ty::Closure(def_id, args) => {
511 let mut s = String::new();
514 let name = encode_ty_name(tcx, *def_id);
515 let _ = write!(s, "u{}{}", name.len(), name);
516 s.push_str(&encode_args(tcx, args, *def_id, false, dict, options));
517 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
518 typeid.push_str(&s);
519 }
520
521 ty::CoroutineClosure(def_id, args) => {
522 let mut s = String::new();
525 let name = encode_ty_name(tcx, *def_id);
526 let _ = write!(s, "u{}{}", name.len(), name);
527 let parent_args = tcx.mk_args(args.as_coroutine_closure().parent_args());
528 s.push_str(&encode_args(tcx, parent_args, *def_id, false, dict, options));
529 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
530 typeid.push_str(&s);
531 }
532
533 ty::Coroutine(def_id, args, ..) => {
534 let mut s = String::new();
537 let name = encode_ty_name(tcx, *def_id);
538 let _ = write!(s, "u{}{}", name.len(), name);
539 s.push_str(&encode_args(
541 tcx,
542 tcx.mk_args(args.as_coroutine().parent_args()),
543 *def_id,
544 false,
545 dict,
546 options,
547 ));
548 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
549 typeid.push_str(&s);
550 }
551
552 ty::Ref(region, ty0, ..) => {
554 let mut s = String::new();
556 s.push_str("u3refI");
557 s.push_str(&encode_ty(tcx, *ty0, dict, options));
558 s.push('E');
559 compress(dict, DictKey::Ty(Ty::new_imm_ref(tcx, *region, *ty0), TyQ::None), &mut s);
560 if ty.is_mutable_ptr() {
561 s = format!("{}{}", "U3mut", s);
562 compress(dict, DictKey::Ty(ty, TyQ::Mut), &mut s);
563 }
564 typeid.push_str(&s);
565 }
566
567 ty::RawPtr(ptr_ty, _mutbl) => {
568 let mut s = String::new();
571 s.push_str(&encode_ty(tcx, *ptr_ty, dict, options));
572 if !ty.is_mutable_ptr() {
573 s = format!("{}{}", "K", s);
574 compress(dict, DictKey::Ty(*ptr_ty, TyQ::Const), &mut s);
575 };
576 s = format!("{}{}", "P", s);
577 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
578 typeid.push_str(&s);
579 }
580
581 ty::FnPtr(sig_tys, hdr) => {
582 let mut s = String::from("P");
584 s.push_str(&encode_fnsig(
585 tcx,
586 &sig_tys.with(*hdr).skip_binder(),
587 dict,
588 TypeIdOptions::empty(),
589 ));
590 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
591 typeid.push_str(&s);
592 }
593
594 ty::UnsafeBinder(_) => {
596 todo!()
597 }
598
599 ty::Dynamic(predicates, region) => {
601 let mut s = String::from("u3dynI");
604 s.push_str(&encode_predicates(tcx, predicates, dict, options));
605 s.push_str(&encode_region(*region, dict));
606 s.push('E');
607 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
608 typeid.push_str(&s);
609 }
610
611 ty::Param(..) => {
613 let mut s = String::from("u5param");
615 compress(dict, DictKey::Ty(ty, TyQ::None), &mut s);
616 typeid.push_str(&s);
617 }
618
619 ty::Alias(..)
621 | ty::Bound(..)
622 | ty::Error(..)
623 | ty::CoroutineWitness(..)
624 | ty::Infer(..)
625 | ty::Placeholder(..) => {
626 bug!("encode_ty: unexpected `{:?}`", ty.kind());
627 }
628 };
629
630 typeid
631}
632
633fn encode_ty_name(tcx: TyCtxt<'_>, def_id: DefId) -> String {
635 let mut s = String::new();
672
673 let mut def_path = tcx.def_path(def_id);
675 def_path.data.reverse();
676 for disambiguated_data in &def_path.data {
677 s.push('N');
678 s.push_str(match disambiguated_data.data {
679 hir::definitions::DefPathData::Impl => "I", hir::definitions::DefPathData::ForeignMod => "F", hir::definitions::DefPathData::TypeNs(..) => "t",
682 hir::definitions::DefPathData::ValueNs(..) => "v",
683 hir::definitions::DefPathData::Closure => "C",
684 hir::definitions::DefPathData::Ctor => "c",
685 hir::definitions::DefPathData::AnonConst => "K",
686 hir::definitions::DefPathData::LateAnonConst => "k",
687 hir::definitions::DefPathData::OpaqueTy => "i",
688 hir::definitions::DefPathData::SyntheticCoroutineBody => "s",
689 hir::definitions::DefPathData::NestedStatic => "n",
690 hir::definitions::DefPathData::CrateRoot
691 | hir::definitions::DefPathData::Use
692 | hir::definitions::DefPathData::GlobalAsm
693 | hir::definitions::DefPathData::MacroNs(..)
694 | hir::definitions::DefPathData::OpaqueLifetime(..)
695 | hir::definitions::DefPathData::LifetimeNs(..)
696 | hir::definitions::DefPathData::DesugaredAnonymousLifetime
697 | hir::definitions::DefPathData::AnonAssocTy(..) => {
698 bug!("encode_ty_name: unexpected `{:?}`", disambiguated_data.data);
699 }
700 });
701 }
702
703 s.push('C');
705 s.push_str(&to_disambiguator(tcx.stable_crate_id(def_path.krate).as_u64()));
706 let crate_name = tcx.crate_name(def_path.krate).to_string();
707 let _ = write!(s, "{}{}", crate_name.len(), crate_name);
708
709 def_path.data.reverse();
711 for disambiguated_data in &def_path.data {
712 let num = disambiguated_data.disambiguator as u64;
713 if num > 0 {
714 s.push_str(&to_disambiguator(num));
715 }
716
717 let name = disambiguated_data.data.to_string();
718 let _ = write!(s, "{}", name.len());
719
720 if let Some(first) = name.as_bytes().first() {
722 if first.is_ascii_digit() || *first == b'_' {
723 s.push('_');
724 }
725 } else {
726 bug!("encode_ty_name: invalid name `{:?}`", name);
727 }
728
729 s.push_str(&name);
730 }
731
732 s
733}
734
735fn to_disambiguator(num: u64) -> String {
738 if let Some(num) = num.checked_sub(1) {
739 format!("s{}_", num.to_base(ALPHANUMERIC_ONLY))
740 } else {
741 "s_".to_string()
742 }
743}
744
745fn to_seq_id(num: usize) -> String {
748 if let Some(num) = num.checked_sub(1) {
749 (num as u64).to_base(CASE_INSENSITIVE).to_uppercase()
750 } else {
751 "".to_string()
752 }
753}