"""Offline Android Binder IPC, AIDL Stub/Proxy Parcel marshaling, Parcelable, and API 21 explicit Service verifier."""
import json
import struct
VERSION = "CPython 3.12.14 offline Android component/IPC/Fragment verifier (Android SDK/emulator absent)"
class SimulatedParcel:
"""Deterministic binary Parcel stream enforcing strict write/read order and interface token check."""
def __init__(self):
self._buf = bytearray()
self._pos = 0
def write_interface_token(self, descriptor: str):
self.write_string(descriptor)
def enforce_interface(self, expected: str):
got = self.read_string()
if got != expected:
raise PermissionError(f"SecurityException: interface mismatch {got} != {expected}")
def write_int(self, val: int):
self._buf.extend(struct.pack(">i", val))
def read_int(self) -> int:
val, = struct.unpack(">i", self._buf[self._pos:self._pos + 4])
self._pos += 4
return val
def write_string(self, s: str | None):
if s is None:
self.write_int(-1)
return
raw = s.encode("utf-8")
self.write_int(len(raw))
self._buf.extend(raw)
def read_string(self) -> str | None:
length = self.read_int()
if length == -1:
return None
raw = bytes(self._buf[self._pos:self._pos + length])
self._pos += length
return raw.decode("utf-8")
def write_no_exception(self):
self.write_int(0)
def read_exception(self):
code = self.read_int()
if code != 0:
raise RuntimeError(f"RemoteException(code={code})")
def case_binder_ipc_architecture_and_copy_semantics():
copy_counts = {
"shared_memory": 0,
"binder": 1,
"socket": 2,
"pipe": 2,
"message_queue": 2,
}
death_notifications = []
class RemoteBinderHandle:
def __init__(self, alive: bool = True):
self.alive = alive
self.recipients = []
def ping_binder(self) -> bool:
return self.alive
def link_to_death(self, cb):
self.recipients.append(cb)
def simulate_process_death(self):
self.alive = False
for cb in self.recipients:
cb()
def transact(self):
if not self.alive:
return "RemoteException"
return "SYNC_OK"
handle = RemoteBinderHandle(alive=True)
handle.link_to_death(lambda: death_notifications.append("binderDied"))
before_death = (handle.ping_binder(), handle.transact())
handle.simulate_process_death()
after_death = (handle.ping_binder(), handle.transact())
actual = {
"ipc_copy_counts": copy_counts,
"before_death": list(before_death),
"after_death": list(after_death),
"death_notifications": death_notifications,
"kernel_uid_pid_trusted": True,
}
expected = {
"ipc_copy_counts": {"shared_memory": 0, "binder": 1, "socket": 2, "pipe": 2, "message_queue": 2},
"before_death": [True, "SYNC_OK"],
"after_death": [False, "RemoteException"],
"death_notifications": ["binderDied"],
"kernel_uid_pid_trusted": True,
}
return {
"name": "binder_ipc_architecture_and_copy_semantics",
"summary": "验证 Binder 一次拷贝性能语义、同步 transact 语义、pingBinder/linkToDeath/RemoteException 远程存活检测机制。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_aidl_simple_query_and_parcel_marshaling():
descriptor = "com.jay.aidl.IPerson"
tx_query_person = 1 # FIRST_CALL_TRANSACTION + 0
names = ["成员A", "成员B", "成员C", "成员D", "成员E"]
class IPersonStub:
def query_local_interface(self, desc: str):
return self if desc == descriptor else None
def query_person(self, num: int) -> str | None:
if 1 <= num <= len(names):
return names[num - 1]
return None
def on_transact(self, code: int, data: SimulatedParcel, reply: SimulatedParcel, flags: int) -> bool:
if code == tx_query_person:
data.enforce_interface(descriptor)
arg0 = data.read_int()
res = self.query_person(arg0)
reply.write_no_exception()
reply.write_string(res)
return True
return False
class IPersonProxy:
def __init__(self, remote_stub: IPersonStub):
self.remote = remote_stub
def query_person(self, num: int) -> str | None:
data = SimulatedParcel()
reply = SimulatedParcel()
data.write_interface_token(descriptor)
data.write_int(num)
self.remote.on_transact(tx_query_person, data, reply, 0)
reply.read_exception()
return reply.read_string()
def as_interface(binder, same_process: bool):
if binder is None:
return None
if same_process:
return binder.query_local_interface(descriptor)
return IPersonProxy(binder)
stub = IPersonStub()
local_iface = as_interface(stub, same_process=True)
remote_proxy = as_interface(stub, same_process=False)
# Note: source AIDLService.onBind accidentally returned null -> asInterface(null) returns null!
null_onbind_result = as_interface(None, same_process=False)
actual = {
"local_is_stub": isinstance(local_iface, IPersonStub),
"remote_is_proxy": isinstance(remote_proxy, IPersonProxy),
"remote_query_3": remote_proxy.query_person(3),
"remote_query_oob": remote_proxy.query_person(9),
"null_onbind_returns_none": null_onbind_result is None,
}
expected = {
"local_is_stub": True,
"remote_is_proxy": True,
"remote_query_3": "成员C",
"remote_query_oob": None,
"null_onbind_returns_none": True,
}
return {
"name": "aidl_simple_query_and_parcel_marshaling",
"summary": "验证 AIDL Stub/Proxy 跨进程 Parcel 编解码、asInterface 同进程直调与跨进程代理分支,以及服务端 onBind 误返回 null 的隐患。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_aidl_complex_parcelable_and_raw_transact():
# Parcelable Person (equality by name) & Salary
class Person:
def __init__(self, pid: int, name: str):
self.id = pid
self.name = name
def write_to_parcel(self, p: SimulatedParcel):
p.write_int(self.id)
p.write_string(self.name)
@staticmethod
def create_from_parcel(p: SimulatedParcel):
return Person(p.read_int(), p.read_string())
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return isinstance(other, Person) and self.name == other.name
class Salary:
def __init__(self, role: str, amount: int):
self.role = role
self.amount = amount
def write_to_parcel(self, p: SimulatedParcel):
p.write_string(self.role)
p.write_int(self.amount)
@staticmethod
def create_from_parcel(p: SimulatedParcel):
return Salary(p.read_string(), p.read_int())
salary_map = {
Person(1, "Jay"): Salary("Engineer", 2000),
Person(2, "GEM"): Salary("Singer", 20000),
}
# Client sends Person(99, "GEM") -> marshaled -> server looks up by name equality
req = SimulatedParcel()
req.write_interface_token("com.jay.example.aidl.ISalary")
Person(99, "GEM").write_to_parcel(req)
rep = SimulatedParcel()
req.enforce_interface("com.jay.example.aidl.ISalary")
owner = Person.create_from_parcel(req)
sal = salary_map[owner]
rep.write_no_exception()
sal.write_to_parcel(rep)
rep.read_exception()
got_sal = Salary.create_from_parcel(rep)
# Direct Binder.onTransact(0x001) without AIDL
raw_names = ["Zero", "One", "Two"]
raw_data = SimulatedParcel()
raw_reply = SimulatedParcel()
raw_data.write_interface_token("IPCService")
raw_data.write_int(2)
raw_data.enforce_interface("IPCService")
idx = raw_data.read_int()
raw_reply.write_no_exception()
raw_reply.write_string(raw_names[idx])
raw_reply.read_exception()
raw_res = raw_reply.read_string()
# Android 5.0+ (API 21) explicit Service Intent rule
def check_service_intent(api_level: int, has_component: bool, has_package: bool) -> str:
if api_level >= 21 and not (has_component or has_package):
return "IllegalArgumentException: Service Intent must be explicit"
return "ALLOWED"
actual = {
"parcelable_salary_role": got_sal.role,
"parcelable_salary_amount": got_sal.amount,
"raw_binder_transact_result": raw_res,
"aidl_direction_tags": ["in", "out", "inout"],
"api21_implicit_service": check_service_intent(21, False, False),
"api21_with_package": check_service_intent(21, False, True),
}
expected = {
"parcelable_salary_role": "Singer",
"parcelable_salary_amount": 20000,
"raw_binder_transact_result": "Two",
"aidl_direction_tags": ["in", "out", "inout"],
"api21_implicit_service": "IllegalArgumentException: Service Intent must be explicit",
"api21_with_package": "ALLOWED",
}
return {
"name": "aidl_complex_parcelable_and_raw_transact",
"summary": "验证复杂 Parcelable(Person/Salary)顺序序列化与哈希键查询、直接 Binder.onTransact 通信,以及 Android 5.0+ 显式 Service Intent 强制校验。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_binder_ipc_architecture_and_copy_semantics(),
case_aidl_simple_query_and_parcel_marshaling(),
case_aidl_complex_parcelable_and_raw_transact(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。
入口文件:projects/android-tutorial-service-3-lab/explore-tutorial-service-3.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-service-3.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 Android 组件/生命周期/IPC/Fragment 确定性验证环境(本地未安装 Android SDK/Gradle/ADB/模拟器)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1942.zip