mach_msg 内核函数的帮助程序在哪里实现或生成?

Where are mach_msg helpers for kernel functions implemented or generated?

与 mach 内核函数的通信使用 mach 消息进行。 libsystem_kernel.dylib 系统库为 send/receive 任意 mach 消息实现了一个 mach_msg(...) 辅助函数,但它也包含准备好的方法来使用某些内核函数,如 task_get_special_port (具有相同的函数名称)。 这可以通过反汇编 lib 二进制文件看到。

可以找到 mach_msg 源代码 here 但像 task_get_special_port 这样的函数特定助手的源代码似乎没有出现在 libsyscall 源代码树中的任何地方。这些 kernelFunction-to-machMsg-adapters 在哪里实现或生成?

另外,在消息和内核函数调用之间进行转换的 mach 消息的接收器在哪里实现? (可以找到 task_get_special_port 的实际内核实现 here

Where are those kernelFunction-to-machMsg-adapters implemented or generated?

它们由 Mach Interface Generator (MIG) 生成。如果您查看扩展名为 .defs 的文件的内核源代码,您可以看到 MIG 用于生成的定义。

Apple Docs中陈述:

At the trap level, the interface to most Mach abstractions consists of messages sent to and from kernel ports representing those objects. The trap-level interfaces (such as mach_msg_overwrite_trap) and message formats are themselves abstracted in normal usage by the Mach Interface Generator (MIG). MIG is used to compile procedural interfaces to the message-based APIs, based on descriptions of those APIs.

对于task_get_special_port,可以看到defs文件here.

如果您对该文件调用 mig,它将生成三个文件。

  • 发件人的 .c 文件 (taskUser.c)
  • 接收器的 .c 文件 (taskServer.c)
  • 定义发送方和接收方之间通信协议的头文件 (task.h)

查看Server.c文件,可以看到这个函数,直接调用task_get_special_port.

mig_internal novalue _Xtask_get_special_port
        (mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP)
{
    ...

        RetCode = task_get_special_port(In0P->Head.msgh_request_port, In0P->which_port, &OutP->special_port.name);
        if (RetCode != KERN_SUCCESS) {
                MIG_RETURN_ERROR(OutP, RetCode);
        }

    ...
}

使用 mig 比必须手动编写客户端和服务器协议更不容易出错。