use super::*;
pub(crate) const PPC_OT_BAD_ADDRESS_ERR: i32 = -3150;
pub(crate) const PPC_OT_BAD_REFERENCE_ERR: i32 = -3153;
pub(crate) const PPC_OT_NOT_FOUND_ERR: i32 = -3201;
pub(crate) const PPC_OT_CONFIGURATION: u32 = PPC_IMPORT_DATA_BASE + 0x450;
pub(crate) const PPC_OT_CLIENT_CONTEXT: u32 = PPC_IMPORT_DATA_BASE + 0x454;
const AF_INET: u16 = 2;
const AF_DNS: u16 = 42;
const MAX_LIST_LINKS: usize = 0x10000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PpcOpenTransportFunction {
Succeed,
Void,
ReturnFirst,
ReturnZero,
ReturnTrue,
InitInContext,
CreateConfiguration,
OpenProvider {
error_arg: usize,
},
NotFound,
BadReference,
InetHostToString,
InetStringToHost,
InitInetAddress,
InitDnsAddress,
InitDdpAddress,
InitNbpAddress,
AddressFromNbpString,
CompareDdpAddresses,
InitNbpEntity,
SetNbpEntityFromAddress,
SetNbpPart {
index: u32,
},
ExtractNbpPart {
index: u32,
},
NbpAddressLength,
AddressFromNbpEntity,
AtomicAdd {
width: u8,
},
AtomicSetBit,
AtomicClearBit,
AtomicTestBit,
CompareAndSwap32,
LifoEnqueue,
LifoDequeue,
LifoStealList,
ReverseList,
BufferDataSize,
ReadBuffer,
AddLast,
RemoveLast,
GetFirst,
GetLast,
IsInList,
RemoveLink,
SubtractTimeStamps,
TimeStampIn {
milliseconds: bool,
},
}
impl PpcOpenTransportFunction {
pub fn from_name(name: &str) -> Option<Self> {
Some(match name {
"InitOpenTransport" | "InitOpenTransportPriv" | "InitOpenTransportUtilities" => {
Self::Succeed
}
"InitOpenTransportInContext" => Self::InitInContext,
"CloseOpenTransport"
| "CloseOpenTransportPriv"
| "CloseOpenTransportInContext"
| "OTExitPatchPriv"
| "OTDestroyConfiguration"
| "OTRemoveNotifier"
| "OTLeaveNotifier"
| "OTIdle"
| "OTEnterInterrupt"
| "OTLeaveInterrupt"
| "OTDestroyTimerTask"
| "OTDestroySystemTask"
| "DisposeOTNotifyUPP" => Self::Void,
"OTCloneConfiguration" => Self::ReturnFirst,
"OTEnterNotifier"
| "OTIsAckingSends"
| "OTFindPortByRef"
| "OTCreateTimerTask"
| "OTCreateTimerTaskInContext"
| "OTCreateSystemTaskPriv"
| "OTScheduleTimerTask"
| "OTScheduleSystemTask"
| "OTCancelTimerTask"
| "OTCancelSystemTask" => Self::ReturnZero,
"OTIsSynchronous" | "OTIsBlocking" => Self::ReturnTrue,
"OTCreateConfiguration" => Self::CreateConfiguration,
"OTOpenEndpointPriv" | "OTOpenEndpointInContext" => Self::OpenProvider { error_arg: 3 },
"OTOpenMapperPriv"
| "OTOpenMapperInContext"
| "OTOpenInternetServicesPriv"
| "OTOpenInternetServicesInContext"
| "OTOpenAppleTalkServicesPriv"
| "OTOpenAppleTalkServicesInContext" => Self::OpenProvider { error_arg: 2 },
"OTAsyncOpenEndpointPriv"
| "OTAsyncOpenEndpointInContext"
| "OTAsyncOpenMapperPriv"
| "OTAsyncOpenMapperInContext"
| "OTAsyncOpenInternetServicesPriv"
| "OTAsyncOpenInternetServicesInContext"
| "OTAsyncOpenAppleTalkServicesPriv"
| "OTAsyncOpenAppleTalkServicesInContext"
| "OTInetGetInterfaceInfo"
| "OTInetGetSecondaryAddresses" => Self::NotFound,
"OTCloseProvider"
| "OTCloseProviderPriv"
| "OTSetSynchronous"
| "OTSetAsynchronous"
| "OTSetBlocking"
| "OTSetNonBlocking"
| "OTInstallNotifier"
| "OTUseSyncIdleEvents"
| "OTIoctl"
| "OTAckSends"
| "OTDontAckSends"
| "OTCancelSynchronousCalls"
| "OTGetEndpointInfo"
| "OTGetEndpointState"
| "OTLook"
| "OTCountDataBytes"
| "OTGetProtAddress"
| "OTResolveAddress"
| "OTBind"
| "OTUnbind"
| "OTConnect"
| "OTRcvConnect"
| "OTListen"
| "OTAccept"
| "OTSndDisconnect"
| "OTSndOrderlyDisconnect"
| "OTRcvDisconnect"
| "OTRcvOrderlyDisconnect"
| "OTRcv"
| "OTSnd"
| "OTRcvUData"
| "OTSndUData"
| "OTRcvUDErr"
| "OTOptionManagement"
| "OTRegisterName"
| "OTDeleteName"
| "OTDeleteNameByID"
| "OTLookupName"
| "OTInetStringToAddress"
| "OTInetAddressToName"
| "OTInetSysInfo"
| "OTInetMailExchange"
| "OTInetQuery"
| "OTATalkGetMyZone"
| "OTATalkGetLocalZones"
| "OTATalkGetZoneList"
| "OTATalkGetInfo" => Self::BadReference,
"OTInetHostToString" => Self::InetHostToString,
"OTInetStringToHost" => Self::InetStringToHost,
"OTInitInetAddress" => Self::InitInetAddress,
"OTInitDNSAddress" => Self::InitDnsAddress,
"OTInitDDPAddress" => Self::InitDdpAddress,
"OTInitNBPAddress" => Self::InitNbpAddress,
"OTSetAddressFromNBPString" => Self::AddressFromNbpString,
"OTCompareDDPAddresses" => Self::CompareDdpAddresses,
"OTInitNBPEntity" => Self::InitNbpEntity,
"OTSetNBPEntityFromAddress" => Self::SetNbpEntityFromAddress,
"OTSetNBPName" => Self::SetNbpPart { index: 0 },
"OTSetNBPType" => Self::SetNbpPart { index: 1 },
"OTSetNBPZone" => Self::SetNbpPart { index: 2 },
"OTExtractNBPName" => Self::ExtractNbpPart { index: 0 },
"OTExtractNBPType" => Self::ExtractNbpPart { index: 1 },
"OTExtractNBPZone" => Self::ExtractNbpPart { index: 2 },
"OTGetNBPEntityLengthAsAddress" => Self::NbpAddressLength,
"OTSetAddressFromNBPEntity" => Self::AddressFromNbpEntity,
"OTAtomicAdd32" => Self::AtomicAdd { width: 4 },
"OTAtomicAdd16" => Self::AtomicAdd { width: 2 },
"OTAtomicAdd8" => Self::AtomicAdd { width: 1 },
"OTAtomicSetBit" => Self::AtomicSetBit,
"OTAtomicClearBit" => Self::AtomicClearBit,
"OTAtomicTestBit" => Self::AtomicTestBit,
"OTCompareAndSwap32" | "OTCompareAndSwapPtr" => Self::CompareAndSwap32,
"OTLIFOEnqueue" | "OTAddFirst" => Self::LifoEnqueue,
"OTLIFODequeue" | "OTRemoveFirst" => Self::LifoDequeue,
"OTLIFOStealList" => Self::LifoStealList,
"OTReverseList" => Self::ReverseList,
"OTBufferDataSize" => Self::BufferDataSize,
"OTReadBuffer" => Self::ReadBuffer,
"OTAddLast" => Self::AddLast,
"OTRemoveLast" => Self::RemoveLast,
"OTGetFirst" => Self::GetFirst,
"OTGetLast" => Self::GetLast,
"OTIsInList" => Self::IsInList,
"OTRemoveLink" => Self::RemoveLink,
"OTSubtractTimeStamps" => Self::SubtractTimeStamps,
"OTTimeStampInMilliseconds" => Self::TimeStampIn { milliseconds: true },
"OTTimeStampInMicroseconds" => Self::TimeStampIn {
milliseconds: false,
},
_ => return None,
})
}
}
fn nbp_part(memory: &mut PpcSectionMem, entity: u32, index: u32) -> Vec<u8> {
let address = entity.wrapping_add(index * 33);
let len = memory.read_u8(address).unwrap_or(0).min(32);
(0..u32::from(len))
.map(|offset| {
memory
.read_u8(address.wrapping_add(1 + offset))
.unwrap_or(0)
})
.collect()
}
fn nbp_store_part(memory: &mut PpcSectionMem, entity: u32, index: u32, bytes: &[u8]) -> bool {
let address = entity.wrapping_add(index * 33);
let len = bytes.len().min(32);
let mut part = [0u8; 33];
part[0] = len as u8;
part[1..1 + len].copy_from_slice(&bytes[..len]);
memory.write_bytes(address, &part).is_some() && bytes.len() <= 32
}
fn nbp_escape(bytes: &[u8]) -> Vec<u8> {
let mut escaped = Vec::new();
for &byte in bytes {
if matches!(byte, b'\\' | b':' | b'@') {
escaped.push(b'\\');
}
escaped.push(byte);
}
escaped
}
fn nbp_address(memory: &mut PpcSectionMem, entity: u32) -> Vec<u8> {
let mut address = nbp_escape(&nbp_part(memory, entity, 0));
address.push(b':');
address.extend(nbp_escape(&nbp_part(memory, entity, 1)));
address.push(b'@');
address.extend(nbp_escape(&nbp_part(memory, entity, 2)));
address
}
fn nbp_string(memory: &mut PpcSectionMem, source: u32, length: i32) -> Option<Vec<u8>> {
if length >= 0 {
let length = length as u32;
if !ppc_memory_can_read_bytes(memory, source, length) {
return None;
}
return (0..length)
.map(|offset| memory.read_u8(source.checked_add(offset)?))
.collect();
}
if length != -1 || source == 0 {
return None;
}
let mut bytes = Vec::new();
let mut cursor = source;
loop {
let byte = memory.read_u8(cursor)?;
if byte == 0 {
return Some(bytes);
}
bytes.push(byte);
cursor = cursor.checked_add(1)?;
}
}
fn read_u32(memory: &mut PpcSectionMem, address: u32) -> u32 {
memory.read_u32_be(address).unwrap_or(0)
}
fn list_links(memory: &mut PpcSectionMem, list: u32) -> Vec<u32> {
let mut links = Vec::new();
let mut link = read_u32(memory, list);
while link != 0 && links.len() < MAX_LIST_LINKS && !links.contains(&link) {
links.push(link);
link = read_u32(memory, link);
}
links
}
fn read_time_stamp(memory: &mut PpcSectionMem, address: u32) -> u64 {
(u64::from(read_u32(memory, address)) << 32) | u64::from(read_u32(memory, address + 4))
}
pub(crate) fn ppc_ot_elapsed(
memory: &mut PpcSectionMem,
start: u32,
now: u64,
milliseconds: bool,
) -> u32 {
let elapsed = now.saturating_sub(read_time_stamp(memory, start));
(if milliseconds {
elapsed / 1000
} else {
elapsed
}) as u32
}
pub(crate) fn ppc_dispatch_open_transport(
function: PpcOpenTransportFunction,
cpu: &PpcCpu,
memory: &mut PpcSectionMem,
) -> PpcImportAction {
use PpcOpenTransportFunction as F;
let status = |value: i32| PpcImportAction::Return(value as u32);
let args = cpu.gpr;
match function {
F::BufferDataSize => {
let size = ot_buffer_chain(memory, args[3])
.and_then(|blocks| {
blocks
.iter()
.try_fold(0u32, |total, block| total.checked_add(block.2))
})
.unwrap_or(0);
PpcImportAction::Return(size)
}
F::ReadBuffer => PpcImportAction::Return(u32::from(ot_read_buffer(
memory, args[3], args[4], args[5],
))),
F::Succeed => status(0),
F::Void => PpcImportAction::ReturnPreserve,
F::ReturnFirst => PpcImportAction::Return(args[3]),
F::ReturnZero => PpcImportAction::Return(0),
F::ReturnTrue => PpcImportAction::Return(1),
F::InitInContext => {
if args[4] != 0 {
let _ = memory.write_u32_be(args[4], PPC_OT_CLIENT_CONTEXT);
}
status(0)
}
F::CreateConfiguration => PpcImportAction::Return(PPC_OT_CONFIGURATION),
F::OpenProvider { error_arg } => {
let error = args[3 + error_arg];
if error != 0 {
let _ = memory.write_u32_be(error, PPC_OT_NOT_FOUND_ERR as u32);
}
PpcImportAction::Return(0)
}
F::NotFound => status(PPC_OT_NOT_FOUND_ERR),
F::BadReference => status(PPC_OT_BAD_REFERENCE_ERR),
F::InetHostToString => {
let text = std::net::Ipv4Addr::from(args[3]).to_string();
let _ = memory.write_bytes(args[4], text.as_bytes());
let _ = memory.write_u8(args[4] + text.len() as u32, 0);
PpcImportAction::ReturnPreserve
}
F::InetStringToHost => {
let text = super::dispatch_stdc::ppc_std_c_string(memory, args[3], 256);
let host = std::str::from_utf8(&text)
.ok()
.and_then(|text| text.trim().parse::<std::net::Ipv4Addr>().ok());
match host {
Some(host) if args[4] != 0 => {
let _ = memory.write_u32_be(args[4], u32::from(host));
status(0)
}
_ => status(PPC_OT_BAD_ADDRESS_ERR),
}
}
F::InitInetAddress => {
let address = args[3];
let _ = memory.write_u16_be(address, AF_INET);
let _ = memory.write_u16_be(address + 2, args[4] as u16);
let _ = memory.write_u32_be(address + 4, args[5]);
let _ = memory.write_bytes(address + 8, &[0; 8]);
PpcImportAction::ReturnPreserve
}
F::InitDdpAddress => {
let mut address = [0u8; 8];
address[..2].copy_from_slice(&0x0100u16.to_be_bytes());
address[2..4].copy_from_slice(&(args[4] as u16).to_be_bytes());
address[4] = args[5] as u8;
address[5] = args[6] as u8;
address[6] = args[7] as u8;
let _ = memory.write_bytes(args[3], &address);
PpcImportAction::ReturnPreserve
}
F::InitNbpAddress | F::AddressFromNbpString => {
let initialize = function == F::InitNbpAddress;
let length = if initialize { -1 } else { args[5] as i32 };
let Some(mut bytes) = nbp_string(memory, args[4], length) else {
return PpcImportAction::Return(0);
};
if initialize {
bytes.splice(..0, 0x0102u16.to_be_bytes());
}
let Ok(count) = u32::try_from(bytes.len()) else {
return PpcImportAction::Return(0);
};
if !ppc_memory_can_write_bytes(memory, args[3], count) {
return PpcImportAction::Return(0);
}
let _ = memory.write_bytes(args[3], &bytes);
PpcImportAction::Return(count)
}
F::CompareDdpAddresses => {
let read = |memory: &mut PpcSectionMem, address: u32| -> Option<[u16; 4]> {
if address == 0 || memory.read_u16_be(address)? != 0x0100 {
return None;
}
Some([
memory.read_u16_be(address.checked_add(2)?)?,
u16::from(memory.read_u8(address.checked_add(4)?)?),
u16::from(memory.read_u8(address.checked_add(5)?)?),
u16::from(memory.read_u8(address.checked_add(6)?)?),
])
};
let equal = read(memory, args[3])
.zip(read(memory, args[4]))
.is_some_and(|(left, right)| {
left.into_iter()
.zip(right)
.all(|(a, b)| a == b || a == 0 || b == 0)
});
PpcImportAction::Return(u32::from(equal))
}
F::InitNbpEntity => {
let _ = memory.write_bytes(args[3], &[0; 99]);
PpcImportAction::ReturnPreserve
}
F::SetNbpPart { index } => {
let bytes = super::dispatch_stdc::ppc_std_c_string(memory, args[4], 33);
PpcImportAction::Return(u32::from(nbp_store_part(memory, args[3], index, &bytes)))
}
F::ExtractNbpPart { index } => {
let mut bytes = nbp_escape(&nbp_part(memory, args[3], index));
bytes.push(0);
let _ = memory.write_bytes(args[4], &bytes);
PpcImportAction::ReturnPreserve
}
F::SetNbpEntityFromAddress => {
let mut parts: [Vec<u8>; 3] = Default::default();
let mut index = 0;
let mut escaped = false;
let mut complete = args[5] <= 0x10000;
for offset in 0..args[5].min(0x10000) {
let Some(byte) = args[4].checked_add(offset).and_then(|p| memory.read_u8(p)) else {
complete = false;
break;
};
if !escaped && byte == b'\\' {
escaped = true;
continue;
}
if !escaped && ((index == 0 && byte == b':') || (index < 2 && byte == b'@')) {
index = if byte == b':' { 1 } else { 2 };
} else if parts[index].len() < 32 {
parts[index].push(byte);
} else {
complete = false;
}
escaped = false;
}
if escaped {
if parts[index].len() < 32 {
parts[index].push(b'\\');
} else {
complete = false;
}
}
for (index, part) in parts.iter().enumerate() {
complete &= nbp_store_part(memory, args[3], index as u32, part);
}
PpcImportAction::Return(u32::from(complete))
}
F::NbpAddressLength => PpcImportAction::Return(nbp_address(memory, args[3]).len() as u32),
F::AddressFromNbpEntity => {
let address = nbp_address(memory, args[4]);
let _ = memory.write_bytes(args[3], &address);
PpcImportAction::Return(address.len() as u32)
}
F::InitDnsAddress => {
let name = super::dispatch_stdc::ppc_std_c_string(memory, args[4], 255);
let _ = memory.write_u16_be(args[3], AF_DNS);
let _ = memory.write_bytes(args[3] + 2, &name);
let _ = memory.write_u8(args[3] + 2 + name.len() as u32, 0);
PpcImportAction::Return(name.len() as u32 + 2)
}
F::AtomicAdd { width } => {
let (delta, address) = (args[3], args[4]);
let value = match width {
4 => {
let value = read_u32(memory, address).wrapping_add(delta);
let _ = memory.write_u32_be(address, value);
value as i32
}
2 => {
let value = memory
.read_u16_be(address)
.unwrap_or(0)
.wrapping_add(delta as u16);
let _ = memory.write_u16_be(address, value);
i32::from(value as i16)
}
_ => {
let value = memory
.read_u8(address)
.unwrap_or(0)
.wrapping_add(delta as u8);
let _ = memory.write_u8(address, value);
i32::from(value as i8)
}
};
status(value)
}
F::AtomicSetBit | F::AtomicClearBit | F::AtomicTestBit => {
let (address, mask) = (args[3], 1u8 << (args[4] & 7));
let byte = memory.read_u8(address).unwrap_or(0);
match function {
F::AtomicSetBit => {
let _ = memory.write_u8(address, byte | mask);
}
F::AtomicClearBit => {
let _ = memory.write_u8(address, byte & !mask);
}
_ => {}
}
PpcImportAction::Return(u32::from(byte & mask != 0))
}
F::CompareAndSwap32 => {
let swapped = read_u32(memory, args[5]) == args[3];
if swapped {
let _ = memory.write_u32_be(args[5], args[4]);
}
PpcImportAction::Return(u32::from(swapped))
}
F::LifoEnqueue => {
let (list, link) = (args[3], args[4]);
let head = read_u32(memory, list);
let _ = memory.write_u32_be(link, head);
let _ = memory.write_u32_be(list, link);
PpcImportAction::ReturnPreserve
}
F::LifoDequeue => {
let list = args[3];
let head = read_u32(memory, list);
if head != 0 {
let next = read_u32(memory, head);
let _ = memory.write_u32_be(list, next);
let _ = memory.write_u32_be(head, 0);
}
PpcImportAction::Return(head)
}
F::LifoStealList => {
let head = read_u32(memory, args[3]);
let _ = memory.write_u32_be(args[3], 0);
PpcImportAction::Return(head)
}
F::ReverseList => {
let (mut previous, mut link, mut steps) = (0, args[3], 0);
while link != 0 && steps < MAX_LIST_LINKS {
let next = read_u32(memory, link);
let _ = memory.write_u32_be(link, previous);
previous = link;
link = next;
steps += 1;
}
PpcImportAction::Return(previous)
}
F::AddLast => {
let (list, link) = (args[3], args[4]);
let _ = memory.write_u32_be(link, 0);
let tail = list_links(memory, list).last().copied().unwrap_or(list);
let _ = memory.write_u32_be(tail, link);
PpcImportAction::ReturnPreserve
}
F::RemoveLast => {
let list = args[3];
let links = list_links(memory, list);
let Some(&last) = links.last() else {
return PpcImportAction::Return(0);
};
let previous = links
.len()
.checked_sub(2)
.map_or(list, |index| links[index]);
let _ = memory.write_u32_be(previous, 0);
PpcImportAction::Return(last)
}
F::GetFirst => PpcImportAction::Return(read_u32(memory, args[3])),
F::GetLast => {
PpcImportAction::Return(list_links(memory, args[3]).last().copied().unwrap_or(0))
}
F::IsInList => {
PpcImportAction::Return(u32::from(list_links(memory, args[3]).contains(&args[4])))
}
F::RemoveLink => {
let (list, link) = (args[3], args[4]);
let links = list_links(memory, list);
let Some(index) = links.iter().position(|&candidate| candidate == link) else {
return PpcImportAction::Return(0);
};
let previous = index.checked_sub(1).map_or(list, |index| links[index]);
let next = read_u32(memory, link);
let _ = memory.write_u32_be(previous, next);
let _ = memory.write_u32_be(link, 0);
PpcImportAction::Return(1)
}
F::SubtractTimeStamps => {
let end = read_time_stamp(memory, args[5]);
let difference = end.wrapping_sub(read_time_stamp(memory, args[4]));
let _ = memory.write_u32_be(args[3], (difference >> 32) as u32);
let _ = memory.write_u32_be(args[3] + 4, difference as u32);
PpcImportAction::Return(args[3])
}
F::TimeStampIn { milliseconds } => {
let value = read_time_stamp(memory, args[3]);
PpcImportAction::Return((if milliseconds { value / 1000 } else { value }) as u32)
}
}
}
fn ot_buffer_chain(memory: &mut PpcSectionMem, mut buffer: u32) -> Option<Vec<(u32, u32, u32)>> {
let mut seen = std::collections::HashSet::new();
let mut blocks = Vec::new();
while buffer != 0 {
if blocks.len() == MAX_LIST_LINKS || !seen.insert(buffer) {
return None;
}
let next = memory.read_u32_be(buffer.checked_add(8)?)?;
let data = memory.read_u32_be(buffer.checked_add(12)?)?;
let length = memory.read_u32_be(buffer.checked_add(16)?)?;
blocks.push((buffer, data, length));
buffer = next;
}
Some(blocks)
}
fn ot_read_buffer(memory: &mut PpcSectionMem, info: u32, output: u32, length_ptr: u32) -> bool {
let read = |memory: &mut PpcSectionMem| -> Option<(Vec<u8>, u32, u32)> {
if !ppc_memory_can_write_bytes(memory, info, 8)
|| !ppc_memory_can_write_bytes(memory, length_ptr, 4)
{
return None;
}
let buffer = memory.read_u32_be(info)?;
let mut offset = memory.read_u32_be(info.checked_add(4)?)?;
let requested = memory.read_u32_be(length_ptr)?;
let blocks = ot_buffer_chain(memory, buffer)?;
let mut bytes = Vec::new();
for (block, data, length) in blocks {
if offset > length {
return None;
}
let count = (length - offset).min(requested - bytes.len() as u32);
for index in 0..count {
bytes.push(memory.read_u8(data.checked_add(offset)?.checked_add(index)?)?);
}
offset += count;
if offset < length {
return Some((bytes, block, offset));
}
offset = 0;
}
Some((bytes, 0, 0))
};
let Some((bytes, buffer, offset)) = read(memory) else {
let _ = memory.write_u32_be(length_ptr, 0);
return true;
};
if !bytes.is_empty() && !ppc_memory_can_write_bytes(memory, output, bytes.len() as u32) {
let _ = memory.write_u32_be(length_ptr, 0);
return true;
}
for (index, byte) in bytes.iter().enumerate() {
let _ = memory.write_u8(output + index as u32, *byte);
}
let _ = memory.write_u32_be(info, buffer);
let _ = memory.write_u32_be(info + 4, offset);
let _ = memory.write_u32_be(length_ptr, bytes.len() as u32);
buffer == 0
}