1use std::collections::{BTreeMap, HashMap};
9use std::path::{Path, PathBuf};
10
11use goblin::mach::Mach;
12use goblin::mach::bind_opcodes::{
13 BIND_IMMEDIATE_MASK, BIND_OPCODE_ADD_ADDR_ULEB, BIND_OPCODE_DO_BIND,
14 BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED, BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB,
15 BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB, BIND_OPCODE_DONE, BIND_OPCODE_MASK,
16 BIND_OPCODE_SET_ADDEND_SLEB, BIND_OPCODE_SET_DYLIB_ORDINAL_IMM,
17 BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB, BIND_OPCODE_SET_DYLIB_SPECIAL_IMM,
18 BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB, BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM,
19 BIND_OPCODE_SET_TYPE_IMM, BIND_SPECIAL_DYLIB_FLAT_LOOKUP, BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE,
20 BIND_SPECIAL_DYLIB_SELF, BIND_SYMBOL_FLAGS_WEAK_IMPORT, BIND_TYPE_POINTER,
21};
22use goblin::mach::load_command::{CommandVariant, DyldInfoCommand};
23use kh_runtime::{GuestMemory, VM_PROT_WRITE, mprotect_darwin, mprotect_rw};
24use scroll::{Sleb128, Uleb128};
25
26use crate::error::LoadError;
27use crate::image::{DylibKind, MachOImage};
28use crate::link::{self, fill_exports};
29use crate::parse::thin_arm64_bytes;
30use crate::session::{ImageLoadStatus, LoadSession, ProcessImage, SkipReason};
31
32#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct BindSite {
35 pub name: String,
37 pub preferred_va: u64,
39 pub addend: i64,
41 pub weak: bool,
43 pub bind_type: u8,
45 pub lib_ordinal: i16,
47 pub is_lazy: bool,
49}
50
51#[derive(Debug)]
57pub struct BindResolveCache {
58 flat: HashMap<String, u64>,
60 install_to_idx: HashMap<String, usize>,
62 basename_to_idx: HashMap<String, usize>,
64 alias_real: HashMap<String, PathBuf>,
66 real_to_idx: HashMap<PathBuf, usize>,
68 deps: Vec<Vec<String>>,
70 missing_named: Option<u64>,
71 missing_anon: Option<u64>,
72}
73
74impl BindResolveCache {
75 #[must_use]
77 pub fn build(images: &[ProcessImage]) -> Self {
78 let mut flat = HashMap::new();
79 let mut install_to_idx = HashMap::new();
80 let mut basename_to_idx = HashMap::new();
81 let mut alias_real = HashMap::new();
82 let mut real_to_idx = HashMap::new();
83 let mut deps = Vec::with_capacity(images.len());
84
85 for (idx, img) in images.iter().enumerate() {
86 let dep_list = img
87 .image
88 .as_ref()
89 .map(dependent_dylib_names)
90 .unwrap_or_default();
91 deps.push(dep_list);
92
93 match &img.status {
94 ImageLoadStatus::Mapped => {
95 let slide = img.slide();
96 if img.export_by_name.is_empty() {
97 for exp in &img.exports {
98 flat.entry(exp.name.clone())
99 .or_insert_with(|| exp.value.wrapping_add(slide));
100 }
101 } else {
102 for (name, &pref) in &img.export_by_name {
103 flat.entry(name.clone())
104 .or_insert_with(|| pref.wrapping_add(slide));
105 }
106 }
107 install_to_idx
108 .entry(img.install_name.clone())
109 .or_insert(idx);
110 if let Some(base) = img.path.file_name().and_then(|n| n.to_str()) {
111 basename_to_idx.entry(base.to_owned()).or_insert(idx);
112 }
113 if !img.real_path.as_os_str().is_empty() {
114 real_to_idx.entry(img.real_path.clone()).or_insert(idx);
115 }
116 }
117 ImageLoadStatus::Skipped(SkipReason::Duplicate) => {
118 alias_real
119 .entry(img.install_name.clone())
120 .or_insert_with(|| img.real_path.clone());
121 }
122 ImageLoadStatus::Skipped(_) => {}
123 }
124 }
125
126 let missing_named = flat.get("_kh_missing_symbol_named").copied();
127 let missing_anon = flat.get("_kh_missing_symbol").copied();
128
129 Self {
130 flat,
131 install_to_idx,
132 basename_to_idx,
133 alias_real,
134 real_to_idx,
135 deps,
136 missing_named,
137 missing_anon,
138 }
139 }
140
141 fn find_mapped_idx(&self, install_name: &str) -> Option<usize> {
142 if let Some(&idx) = self.install_to_idx.get(install_name) {
143 return Some(idx);
144 }
145 if let Some(base) = Path::new(install_name).file_name().and_then(|n| n.to_str())
147 && let Some(&idx) = self.basename_to_idx.get(base)
148 {
149 return Some(idx);
150 }
151 let alias_key = self.alias_real.get(install_name)?;
152 if alias_key.as_os_str().is_empty() {
153 return None;
154 }
155 self.real_to_idx.get(alias_key).copied()
156 }
157
158 fn dep_name(&self, binder_idx: usize, ordinal: u32) -> Result<&str, LoadError> {
159 let deps = self.deps.get(binder_idx).ok_or(LoadError::NotImplemented(
160 "binder image missing for bind resolve",
161 ))?;
162 let idx = ordinal
163 .checked_sub(1)
164 .and_then(|i| usize::try_from(i).ok())
165 .ok_or_else(|| LoadError::Resolve(format!("invalid dylib ordinal {ordinal}")))?;
166 deps.get(idx).map(String::as_str).ok_or_else(|| {
167 LoadError::Resolve(format!(
168 "dylib ordinal {ordinal} out of range ({} deps)",
169 deps.len()
170 ))
171 })
172 }
173}
174
175pub fn bind_process(session: &mut LoadSession) -> Result<(), LoadError> {
184 crate::load_timing::time_result("bind_fill_exports", || fill_exports(session))?;
185 let cache = crate::load_timing::time(
186 "bind_resolve_cache",
187 || BindResolveCache::build(session.images()),
188 );
189
190 let n = session.images.len();
191 let mut used_any = false;
192 for idx in 0..n {
193 let mapped = session
194 .images
195 .get(idx)
196 .is_some_and(|i| matches!(i.status, ImageLoadStatus::Mapped));
197 if !mapped {
198 continue;
199 }
200 let container =
202 if let Some(b) = session.images.get_mut(idx).and_then(|i| i.file_bytes.take()) {
203 b
204 } else {
205 let path = session
206 .images
207 .get(idx)
208 .map(|i| i.path.clone())
209 .unwrap_or_default();
210 if path.as_os_str().is_empty() {
211 continue;
212 }
213 crate::load_timing::time_result("bind_reread_file", || {
214 crate::FileImage::open(&path)
215 })?
216 };
217 if crate::chained::bytes_have_chained_fixups(container.as_slice())? {
220 crate::load_timing::time_result("bind_chained", || {
221 crate::chained::apply_chained_fixups(
222 session,
223 idx,
224 container.as_slice(),
225 &cache,
226 )
227 })?;
228 used_any = true;
229 continue;
230 }
231 let sites = crate::load_timing::time_result("bind_collect_sites", || {
232 collect_bind_sites(container.as_slice())
233 })?;
234 if sites.is_empty() {
235 continue;
236 }
237 used_any = true;
238 crate::load_timing::time_result("bind_apply_sites", || {
239 apply_bind_sites(session, idx, &sites, &cache)
240 })?;
241 drop(container);
242 }
243
244 if !used_any {
245 link::bind_main_got_nlist(session)?;
246 }
247 crate::missing_stub::seal_pool();
248 Ok(())
249}
250
251fn resolve_missing_stub(cache: &BindResolveCache, name: &str) -> Result<u64, LoadError> {
254 if let Some(handler) = cache.missing_named {
255 match crate::missing_stub::trampoline_for(name, handler) {
256 Ok(va) => {
257 tracing::debug!(
259 name = %name,
260 stub = format_args!("{va:#x}"),
261 "unresolved strong symbol; bound to named missing trampoline"
262 );
263 return Ok(va);
264 }
265 Err(err) => {
266 tracing::warn!(
267 name = %name,
268 error = %err,
269 "missing trampoline emit failed; falling back"
270 );
271 }
272 }
273 }
274 if let Some(stub) = cache.missing_anon {
275 tracing::debug!(
276 name = %name,
277 "unresolved strong symbol; bound to _kh_missing_symbol"
278 );
279 return Ok(stub);
280 }
281 if let Some(handler) = cache.missing_named {
282 tracing::debug!(
284 name = %name,
285 "unresolved strong symbol; bound to _kh_missing_symbol_named (no trampoline)"
286 );
287 return Ok(handler);
288 }
289 Err(LoadError::UnresolvedSymbol {
290 name: name.to_owned(),
291 })
292}
293
294pub fn collect_bind_sites(bytes: &[u8]) -> Result<Vec<BindSite>, LoadError> {
299 let thin = thin_arm64_bytes(bytes)?;
300 let macho = match Mach::parse(thin) {
301 Ok(Mach::Binary(m)) => m,
302 Ok(Mach::Fat(_)) => {
303 return Err(LoadError::NotMachO(
304 "nested fat image inside arm64 slice".into(),
305 ));
306 }
307 Err(err) => return Err(LoadError::NotMachO(err.to_string())),
308 };
309
310 let Some(cmd) = dyld_info_command(&macho) else {
311 return Ok(Vec::new());
312 };
313
314 let seg_vmaddrs: Vec<u64> = macho.segments.iter().map(|s| s.vmaddr).collect();
315 let mut sites = Vec::new();
316
317 if cmd.bind_size > 0 {
318 let range = file_range(cmd.bind_off, cmd.bind_size, thin.len())?;
319 interpret_stream(thin, range, false, &seg_vmaddrs, &mut sites)?;
320 }
321 if cmd.lazy_bind_size > 0 {
322 let range = file_range(cmd.lazy_bind_off, cmd.lazy_bind_size, thin.len())?;
323 interpret_stream(thin, range, true, &seg_vmaddrs, &mut sites)?;
324 }
325
326 Ok(sites)
327}
328
329fn dyld_info_command<'a>(macho: &'a goblin::mach::MachO<'a>) -> Option<&'a DyldInfoCommand> {
330 for lc in &macho.load_commands {
331 match &lc.command {
332 CommandVariant::DyldInfo(c) | CommandVariant::DyldInfoOnly(c) => return Some(c),
333 _ => {}
334 }
335 }
336 None
337}
338
339fn file_range(off: u32, size: u32, len: usize) -> Result<std::ops::Range<usize>, LoadError> {
340 let start = usize::try_from(off).map_err(|_| LoadError::Resolve("bind off overflow".into()))?;
341 let size =
342 usize::try_from(size).map_err(|_| LoadError::Resolve("bind size overflow".into()))?;
343 let end = start
344 .checked_add(size)
345 .ok_or_else(|| LoadError::Resolve("bind range overflow".into()))?;
346 if end > len {
347 return Err(LoadError::Resolve(format!(
348 "bind stream {start:#x}..{end:#x} past file end {len:#x}"
349 )));
350 }
351 Ok(start..end)
352}
353
354#[derive(Clone)]
355struct BindState {
356 seg_index: u8,
357 seg_offset: u64,
358 bind_type: u8,
359 lib_ordinal: i16,
360 symbol_name: String,
361 symbol_flags: u8,
362 addend: i64,
363}
364
365impl BindState {
366 fn new(is_lazy: bool) -> Self {
367 Self {
368 seg_index: 0,
369 seg_offset: 0,
370 bind_type: if is_lazy { BIND_TYPE_POINTER } else { 0 },
371 lib_ordinal: 0,
372 symbol_name: String::new(),
373 symbol_flags: 0,
374 addend: 0,
375 }
376 }
377
378 fn is_weak(&self) -> bool {
379 self.symbol_flags & BIND_SYMBOL_FLAGS_WEAK_IMPORT != 0
380 }
381}
382
383fn interpret_stream(
384 data: &[u8],
385 range: std::ops::Range<usize>,
386 is_lazy: bool,
387 seg_vmaddrs: &[u64],
388 out: &mut Vec<BindSite>,
389) -> Result<(), LoadError> {
390 const PTR_SIZE: u64 = 8;
391 let mut state = BindState::new(is_lazy);
392 let mut offset = range.start;
393
394 while offset < range.end {
395 let opcode_byte = *data
396 .get(offset)
397 .ok_or_else(|| LoadError::Resolve("bind stream truncated".into()))?;
398 offset = offset.saturating_add(1);
399 let opcode = opcode_byte & BIND_OPCODE_MASK;
400 let imm = opcode_byte & BIND_IMMEDIATE_MASK;
401
402 match opcode {
403 BIND_OPCODE_DONE => {
404 state = BindState::new(is_lazy);
405 }
406 BIND_OPCODE_SET_DYLIB_ORDINAL_IMM => {
407 state.lib_ordinal = i16::from(imm);
408 }
409 BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB => {
410 let v = read_uleb(data, &mut offset)?;
411 state.lib_ordinal = i16::try_from(v).map_err(|_| {
412 LoadError::Resolve(format!("bind dylib ordinal too large: {v}"))
413 })?;
414 }
415 BIND_OPCODE_SET_DYLIB_SPECIAL_IMM => {
416 if imm == 0 {
418 state.lib_ordinal = i16::from(BIND_SPECIAL_DYLIB_SELF);
419 } else {
420 let raw = BIND_OPCODE_MASK | imm;
421 let sign_ext = raw.cast_signed();
422 state.lib_ordinal = i16::from(sign_ext);
423 }
424 }
425 BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM => {
426 state.symbol_flags = imm;
427 let name = read_cstring(data, &mut offset, range.end)?;
428 state.symbol_name = name;
429 }
430 BIND_OPCODE_SET_TYPE_IMM => {
431 state.bind_type = imm;
432 }
433 BIND_OPCODE_SET_ADDEND_SLEB => {
434 state.addend = read_sleb(data, &mut offset)?;
435 }
436 BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB => {
437 state.seg_index = imm;
438 state.seg_offset = read_uleb(data, &mut offset)?;
439 }
440 BIND_OPCODE_ADD_ADDR_ULEB => {
441 let addr = read_uleb(data, &mut offset)?;
442 state.seg_offset = state.seg_offset.wrapping_add(addr);
443 }
444 BIND_OPCODE_DO_BIND => {
445 push_site(&state, is_lazy, seg_vmaddrs, out)?;
446 state.seg_offset = state.seg_offset.wrapping_add(PTR_SIZE);
447 }
448 BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB => {
449 push_site(&state, is_lazy, seg_vmaddrs, out)?;
450 let addr = read_uleb(data, &mut offset)?;
451 state.seg_offset = state.seg_offset.wrapping_add(addr).wrapping_add(PTR_SIZE);
452 }
453 BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED => {
454 push_site(&state, is_lazy, seg_vmaddrs, out)?;
455 let scale = u64::from(imm);
456 state.seg_offset = state
457 .seg_offset
458 .wrapping_add(scale.wrapping_mul(PTR_SIZE))
459 .wrapping_add(PTR_SIZE);
460 }
461 BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB => {
462 let count = read_uleb(data, &mut offset)?;
463 let skip = read_uleb(data, &mut offset)?;
464 let step = skip.wrapping_add(PTR_SIZE);
465 for _ in 0..count {
466 push_site(&state, is_lazy, seg_vmaddrs, out)?;
467 state.seg_offset = state.seg_offset.wrapping_add(step);
468 }
469 }
470 _ => {
471 return Err(LoadError::Resolve(format!(
472 "unknown bind opcode {opcode_byte:#x}"
473 )));
474 }
475 }
476 }
477 Ok(())
478}
479
480fn push_site(
481 state: &BindState,
482 is_lazy: bool,
483 seg_vmaddrs: &[u64],
484 out: &mut Vec<BindSite>,
485) -> Result<(), LoadError> {
486 if state.symbol_name.is_empty() {
487 return Err(LoadError::Resolve(
488 "bind DO_BIND without symbol name".into(),
489 ));
490 }
491 let seg_i = usize::from(state.seg_index);
492 let seg_base = *seg_vmaddrs.get(seg_i).ok_or_else(|| {
493 LoadError::Resolve(format!(
494 "bind segment index {} out of range ({})",
495 state.seg_index,
496 seg_vmaddrs.len()
497 ))
498 })?;
499 let preferred_va = seg_base.wrapping_add(state.seg_offset);
500 out.push(BindSite {
501 name: state.symbol_name.clone(),
502 preferred_va,
503 addend: state.addend,
504 weak: state.is_weak(),
505 bind_type: state.bind_type,
506 lib_ordinal: state.lib_ordinal,
507 is_lazy,
508 });
509 Ok(())
510}
511
512fn read_uleb(data: &[u8], offset: &mut usize) -> Result<u64, LoadError> {
513 Uleb128::read(data, offset).map_err(|err| LoadError::Resolve(format!("bind uleb: {err}")))
514}
515
516fn read_sleb(data: &[u8], offset: &mut usize) -> Result<i64, LoadError> {
517 Sleb128::read(data, offset).map_err(|err| LoadError::Resolve(format!("bind sleb: {err}")))
518}
519
520fn read_cstring(data: &[u8], offset: &mut usize, end: usize) -> Result<String, LoadError> {
521 let start = *offset;
522 if start >= end {
523 return Err(LoadError::Resolve(
524 "bind symbol name past stream end".into(),
525 ));
526 }
527 let slice = data
528 .get(start..end)
529 .ok_or_else(|| LoadError::Resolve("bind symbol name OOB".into()))?;
530 let nul = slice
531 .iter()
532 .position(|&b| b == 0)
533 .ok_or_else(|| LoadError::Resolve("bind symbol name not NUL-terminated".into()))?;
534 let name_bytes = slice
535 .get(..nul)
536 .ok_or_else(|| LoadError::Resolve("bind symbol name slice OOB".into()))?;
537 let name = std::str::from_utf8(name_bytes)
538 .map_err(|err| LoadError::Resolve(format!("bind symbol utf8: {err}")))?
539 .to_owned();
540 *offset = start.saturating_add(nul).saturating_add(1);
541 Ok(name)
542}
543
544fn apply_bind_sites(
545 session: &mut LoadSession,
546 image_idx: usize,
547 sites: &[BindSite],
548 cache: &BindResolveCache,
549) -> Result<(), LoadError> {
550 let slide = session.images.get(image_idx).map_or(0, ProcessImage::slide);
551
552 let mut updates: Vec<(u64, u64)> = Vec::with_capacity(sites.len());
553 for site in sites {
554 if site.bind_type != BIND_TYPE_POINTER && site.bind_type != 0 {
556 return Err(LoadError::NotImplemented(
557 "non-POINTER classic bind type (TEXT absolute/pcrel)",
558 ));
559 }
560 let resolved = resolve_bind_symbol(cache, session.images(), image_idx, site)?;
561 let value = if site.addend == 0 {
562 resolved
563 } else {
564 resolved.wrapping_add(site.addend.cast_unsigned())
565 };
566 let slot = site.preferred_va.wrapping_add(slide);
567 tracing::debug!(
568 name = %site.name,
569 slot,
570 value,
571 ordinal = site.lib_ordinal,
572 lazy = site.is_lazy,
573 "bind opcode POINTER"
574 );
575 updates.push((slot, value));
576 }
577
578 write_pointer_slots(session, image_idx, &updates)
579}
580
581pub(crate) fn resolve_bind_symbol(
583 cache: &BindResolveCache,
584 images: &[ProcessImage],
585 binder_idx: usize,
586 site: &BindSite,
587) -> Result<u64, LoadError> {
588 match resolve_bind_symbol_inner(cache, images, binder_idx, site) {
589 Ok(va) => Ok(va),
590 Err(LoadError::UnresolvedSymbol { name }) if !site.weak => {
591 resolve_missing_stub(cache, &name)
596 }
597 Err(err) => Err(err),
598 }
599}
600
601fn resolve_bind_symbol_inner(
602 cache: &BindResolveCache,
603 images: &[ProcessImage],
604 binder_idx: usize,
605 site: &BindSite,
606) -> Result<u64, LoadError> {
607 match site.lib_ordinal {
611 o if o == i16::from(BIND_SPECIAL_DYLIB_SELF) => {
612 lookup_in_image(images.get(binder_idx), &site.name, site.weak)
613 }
614 -1 => {
615 debug_assert_eq!(BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE, 0xf);
617 lookup_in_image(images.first(), &site.name, site.weak)
618 }
619 -2 => {
620 debug_assert_eq!(BIND_SPECIAL_DYLIB_FLAT_LOOKUP, 0xe);
622 lookup_flat(cache, &site.name, site.weak)
623 }
624 -3 => {
625 lookup_flat(cache, &site.name, site.weak)
629 }
630 n if n > 0 => {
631 let ordinal_u32 = u32::try_from(n)
632 .map_err(|_| LoadError::Resolve(format!("bind ordinal out of u32 range: {n}")))?;
633 let dep_name = cache.dep_name(binder_idx, ordinal_u32)?;
634 if let Some(idx) = cache.find_mapped_idx(dep_name) {
635 lookup_in_image(images.get(idx), &site.name, site.weak)
636 } else if site.weak {
637 Ok(0)
638 } else if let Ok(va) = lookup_flat(cache, &site.name, false) {
639 tracing::debug!(
642 name = %site.name,
643 missing = %dep_name,
644 "two-level target missing; flat stub resolve"
645 );
646 Ok(va)
647 } else {
648 Err(LoadError::UnresolvedSymbol {
650 name: site.name.clone(),
651 })
652 }
653 }
654 other => Err(LoadError::Resolve(format!(
655 "unsupported bind library ordinal {other}"
656 ))),
657 }
658}
659
660fn dependent_dylib_names(image: &MachOImage) -> Vec<String> {
661 image
662 .dylibs
663 .iter()
664 .filter(|d| d.kind != DylibKind::Id)
665 .map(|d| d.name.clone())
666 .collect()
667}
668
669fn lookup_in_image(img: Option<&ProcessImage>, name: &str, weak: bool) -> Result<u64, LoadError> {
670 let Some(img) = img else {
671 return if weak {
672 Ok(0)
673 } else {
674 Err(LoadError::UnresolvedSymbol {
675 name: name.to_owned(),
676 })
677 };
678 };
679 if !matches!(img.status, ImageLoadStatus::Mapped) {
680 return if weak {
681 Ok(0)
682 } else {
683 Err(LoadError::UnresolvedSymbol {
684 name: name.to_owned(),
685 })
686 };
687 }
688 let slide = img.slide();
689 if let Some(&pref) = img.export_by_name.get(name) {
690 return Ok(pref.wrapping_add(slide));
691 }
692 if img.export_by_name.is_empty()
694 && let Some(exp) = img.exports.iter().find(|e| e.name == name)
695 {
696 return Ok(exp.value.wrapping_add(slide));
697 }
698 if weak {
699 Ok(0)
700 } else {
701 Err(LoadError::UnresolvedSymbol {
702 name: name.to_owned(),
703 })
704 }
705}
706
707fn lookup_flat(cache: &BindResolveCache, name: &str, weak: bool) -> Result<u64, LoadError> {
708 match cache.flat.get(name) {
709 Some(&va) => Ok(va),
710 None if weak => Ok(0),
711 None => Err(LoadError::UnresolvedSymbol {
712 name: name.to_owned(),
713 }),
714 }
715}
716
717pub(crate) fn write_pointer_slots(
723 session: &mut LoadSession,
724 image_idx: usize,
725 updates: &[(u64, u64)],
726) -> Result<(), LoadError> {
727 if updates.is_empty() {
728 return Ok(());
729 }
730 let img = session
731 .images
732 .get_mut(image_idx)
733 .ok_or(LoadError::NotImplemented("image missing for bind write"))?;
734 let memory = img
735 .memory
736 .as_mut()
737 .ok_or(LoadError::NotImplemented("memory missing for bind write"))?;
738 write_slots_batched(memory, updates)
739}
740
741pub(crate) fn write_slots_batched(
743 memory: &mut GuestMemory,
744 updates: &[(u64, u64)],
745) -> Result<(), LoadError> {
746 if updates.is_empty() {
747 return Ok(());
748 }
749
750 let mut by_region: BTreeMap<usize, Vec<(u64, u64)>> = BTreeMap::new();
752 for &(slot, value) in updates {
753 let region_idx = memory
754 .regions()
755 .iter()
756 .position(|r| {
757 let start = r.guest_addr;
758 let end = start.saturating_add(r.vmsize);
759 slot >= start && slot < end
760 })
761 .ok_or_else(|| {
762 LoadError::Resolve(format!("bind slot {slot:#x} outside mapped regions"))
763 })?;
764 by_region.entry(region_idx).or_default().push((slot, value));
765 }
766
767 for (region_idx, slots) in by_region {
768 let restore = memory
769 .regions()
770 .get(region_idx)
771 .ok_or_else(|| LoadError::Resolve(format!("bind region missing idx {region_idx}")))?
772 .prot;
773 let need_flip = restore & VM_PROT_WRITE == 0;
775 if need_flip {
776 let region = memory.regions_mut().get_mut(region_idx).ok_or_else(|| {
777 LoadError::Resolve(format!("bind region missing idx {region_idx}"))
778 })?;
779 mprotect_rw(region).map_err(LoadError::Map)?;
780 }
781
782 for (slot, value) in slots {
783 if memory.write_u64_le(slot, value).is_none() {
784 return Err(LoadError::Resolve(format!(
785 "bind write failed at {slot:#x}"
786 )));
787 }
788 }
789
790 if need_flip {
791 let region = memory
792 .regions()
793 .get(region_idx)
794 .ok_or_else(|| LoadError::Resolve(format!("bind region lost idx {region_idx}")))?;
795 mprotect_darwin(region, restore).map_err(LoadError::Map)?;
796 }
797 }
798 Ok(())
799}
800
801#[must_use]
803pub fn encode_pointer_bind(
804 dylib_ordinal: u8,
805 symbol: &str,
806 seg_index: u8,
807 seg_offset: u64,
808) -> Vec<u8> {
809 let mut out = Vec::with_capacity(32);
810 out.push(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | (dylib_ordinal & BIND_IMMEDIATE_MASK));
811 out.push(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER);
812 out.push(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM);
813 out.extend_from_slice(symbol.as_bytes());
814 out.push(0);
815 out.push(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | (seg_index & BIND_IMMEDIATE_MASK));
816 push_uleb(&mut out, seg_offset);
817 out.push(BIND_OPCODE_DO_BIND);
818 out.push(BIND_OPCODE_DONE);
819 out
820}
821
822fn push_uleb(out: &mut Vec<u8>, mut value: u64) {
823 loop {
824 let mut byte = u8::try_from(value & 0x7f).unwrap_or(0);
825 value >>= 7;
826 if value != 0 {
827 byte |= 0x80;
828 }
829 out.push(byte);
830 if value == 0 {
831 break;
832 }
833 }
834}
835
836#[cfg(test)]
837#[allow(clippy::expect_used, clippy::unwrap_used)]
838mod tests {
839 use super::*;
840
841 #[test]
842 fn encode_and_collect_one_site() {
843 const GOT_VA: u64 = 0x1_0000_4000;
844 let stream = encode_pointer_bind(1, "_kh_add", 2, 0);
845 let seg = [0_u64, 0x1_0000_0000, GOT_VA];
846 let mut sites = Vec::new();
847 interpret_stream(&stream, 0..stream.len(), false, &seg, &mut sites).expect("interp");
848 assert_eq!(sites.len(), 1);
849 let s = sites.first().expect("one");
850 assert_eq!(s.name, "_kh_add");
851 assert_eq!(s.preferred_va, GOT_VA);
852 assert_eq!(s.lib_ordinal, 1);
853 assert_eq!(s.bind_type, BIND_TYPE_POINTER);
854 assert!(!s.weak);
855 assert!(!s.is_lazy);
856 }
857
858 #[test]
859 fn do_bind_times_skipping() {
860 let mut stream = Vec::new();
863 stream.push(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | 1);
864 stream.push(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER);
865 stream.push(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM);
866 stream.extend_from_slice(b"x\0");
867 stream.push(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB);
868 push_uleb(&mut stream, 0);
869 stream.push(BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB);
870 push_uleb(&mut stream, 2);
871 push_uleb(&mut stream, 8);
872 stream.push(BIND_OPCODE_DONE);
873
874 let seg = [0x1000_u64];
875 let mut sites = Vec::new();
876 interpret_stream(&stream, 0..stream.len(), false, &seg, &mut sites).expect("interp");
877 assert_eq!(sites.len(), 2);
878 assert_eq!(sites.first().expect("0").preferred_va, 0x1000);
879 assert_eq!(sites.get(1).expect("1").preferred_va, 0x1000 + 16);
880 }
881}