当前位置:   article > 正文

XNU内核源码分析(一):XNU内核初探

xnu内核

        XNU(全称XNU's not Unix)是macOS及iOS操作系统的内核,由苹果公司开发。它是一个混合内核,分为两层:Mach层和BSD层。Mach层是系统底层,提供任务调度、进程间通信和内存管理等最基本的功能,还有IOKit框架和libkern,方便开发者将驱动插入Mach层。BSD层建立在Mach层之上,提供Unix系统调用、网络、文件系统和安全等高级功能。XNU内核的结构如下图所示:

(图片来源:Mac OS X And iOS Internals,引自macOS 进化史 | zhangferry的技术博客

        从Apple Open Source下载xnu-8019.61.5(我已上传到CSDN,也可以在CSDN上免费下载:https://download.csdn.net/download/2301_76160635/88683218),解压后的目录如下图所示:

        要编译XNU内核,可参考这篇文章:XNU内核编译简要教程 | 老牛的技术田地。文章中提到的库可以从Apple Open Source下载,也可以从CSDN下载。我已上传到CSDN,将下载地址汇集到下表:

       

        下载完成后,我们参考网上的教程,编译出XNU内核。我们现在对XNU内核还不熟悉,不知道这些目录是干什么的。这个时候,我们就要打开README.md,去查看详细信息。当我们刚拿到一个项目,感到茫然的时候,可以先打开README文件,初步地了解它。

        README.md的内容如下:

  1. What is XNU?
  2. ===========
  3. XNU kernel is part of the Darwin operating system for use in macOS and iOS operating systems. XNU is an acronym for X is Not Unix.
  4. XNU is a hybrid kernel combining the Mach kernel developed at Carnegie Mellon University with components from FreeBSD and a C++ API for writing drivers called IOKit.
  5. XNU runs on x86_64 for both single processor and multi-processor configurations.
  6. XNU Source Tree
  7. ===============
  8. * `config` - configurations for exported apis for supported architecture and platform
  9. * `SETUP` - Basic set of tools used for configuring the kernel, versioning and kextsymbol management.
  10. * `EXTERNAL_HEADERS` - Headers sourced from other projects to avoid dependency cycles when building. These headers should be regularly synced when source is updated.
  11. * `libkern` - C++ IOKit library code for handling of drivers and kexts.
  12. * `libsa` - kernel bootstrap code for startup
  13. * `libsyscall` - syscall library interface for userspace programs
  14. * `libkdd` - source for user library for parsing kernel data like kernel chunked data.
  15. * `makedefs` - top level rules and defines for kernel build.
  16. * `osfmk` - Mach kernel based subsystems
  17. * `pexpert` - Platform specific code like interrupt handling, atomics etc.
  18. * `security` - Mandatory Access Check policy interfaces and related implementation.
  19. * `bsd` - BSD subsystems code
  20. * `tools` - A set of utilities for testing, debugging and profiling kernel.
  21. How to build XNU
  22. ================
  23. Building `DEVELOPMENT` kernel
  24. -----------------------------
  25. The xnu make system can build kernel based on `KERNEL_CONFIGS` & `ARCH_CONFIGS` variables as arguments.
  26. Here is the syntax:
  27. make SDKROOT=<sdkroot> ARCH_CONFIGS=<arch> KERNEL_CONFIGS=<variant>
  28. Where:
  29. * \<sdkroot>: path to macOS SDK on disk. (defaults to `/`)
  30. * \<variant>: can be `debug`, `development`, `release`, `profile` and configures compilation flags and asserts throughout kernel code.
  31. * \<arch> : can be valid arch to build for. (E.g. `X86_64`)
  32. To build a kernel for the same architecture as running OS, just type
  33. $ make
  34. $ make SDKROOT=macosx.internal
  35. Additionally, there is support for configuring architectures through `ARCH_CONFIGS` and kernel configurations with `KERNEL_CONFIGS`.
  36. $ make SDKROOT=macosx.internal ARCH_CONFIGS=X86_64 KERNEL_CONFIGS=DEVELOPMENT
  37. $ make SDKROOT=macosx.internal ARCH_CONFIGS=X86_64 KERNEL_CONFIGS="RELEASE DEVELOPMENT DEBUG"
  38. Note:
  39. * By default, architecture is set to the build machine architecture, and the default kernel
  40. config is set to build for DEVELOPMENT.
  41. This will also create a bootable image, kernel.[config], and a kernel binary
  42. with symbols, kernel.[config].unstripped.
  43. To intall the kernel into a DSTROOT, use the `install_kernels` target:
  44. $ make install_kernels DSTROOT=/tmp/xnu-dst
  45. Hint:
  46. For a more satisfying kernel debugging experience, with access to all
  47. local variables and arguments, but without all the extra check of the
  48. DEBUG kernel, add something like:
  49. CFLAGS_DEVELOPMENTARM64="-O0 -g -DKERNEL_STACK_MULTIPLIER=2"
  50. CXXFLAGS_DEVELOPMENTARM64="-O0 -g -DKERNEL_STACK_MULTIPLIER=2"
  51. to your make command.
  52. Replace DEVELOPMENT and ARM64 with the appropriate build and platform.
  53. * To build with RELEASE kernel configuration
  54. make KERNEL_CONFIGS=RELEASE SDKROOT=/path/to/SDK
  55. Building FAT kernel binary
  56. --------------------------
  57. Define architectures in your environment or when running a make command.
  58. $ make ARCH_CONFIGS="X86_64" exporthdrs all
  59. Other makefile options
  60. ----------------------
  61. * $ make MAKEJOBS=-j8 # this will use 8 processes during the build. The default is 2x the number of active CPUS.
  62. * $ make -j8 # the standard command-line option is also accepted
  63. * $ make -w # trace recursive make invocations. Useful in combination with VERBOSE=YES
  64. * $ make BUILD_LTO=0 # build without LLVM Link Time Optimization
  65. * $ make BOUND_CHECKS=1 # enable -fbound-attributes for this build
  66. * $ make REMOTEBUILD=user@remotehost # perform build on remote host
  67. * $ make BUILD_JSON_COMPILATION_DATABASE=1 # Build Clang JSON Compilation Database
  68. The XNU build system can optionally output color-formatted build output. To enable this, you can either
  69. set the `XNU_LOGCOLORS` environment variable to `y`, or you can pass `LOGCOLORS=y` to the make command.
  70. Debug information formats
  71. =========================
  72. By default, a DWARF debug information repository is created during the install phase; this is a "bundle" named kernel.development.\<variant>.dSYM
  73. To select the older STABS debug information format (where debug information is embedded in the kernel.development.unstripped image), set the BUILD_STABS environment variable.
  74. $ export BUILD_STABS=1
  75. $ make
  76. Building KernelCaches
  77. =====================
  78. To test the xnu kernel, you need to build a kernelcache that links the kexts and
  79. kernel together into a single bootable image.
  80. To build a kernelcache you can use the following mechanisms:
  81. * Using automatic kernelcache generation with `kextd`.
  82. The kextd daemon keeps watching for changing in `/System/Library/Extensions` directory.
  83. So you can setup new kernel as
  84. $ cp BUILD/obj/DEVELOPMENT/X86_64/kernel.development /System/Library/Kernels/
  85. $ touch /System/Library/Extensions
  86. $ ps -e | grep kextd
  87. * Manually invoking `kextcache` to build new kernelcache.
  88. $ kextcache -q -z -a x86_64 -l -n -c /var/tmp/kernelcache.test -K /var/tmp/kernel.test /System/Library/Extensions
  89. Running KernelCache on Target machine
  90. =====================================
  91. The development kernel and iBoot supports configuring boot arguments so that we can safely boot into test kernel and, if things go wrong, safely fall back to previously used kernelcache.
  92. Following are the steps to get such a setup:
  93. 1. Create kernel cache using the kextcache command as `/kernelcache.test`
  94. 2. Copy exiting boot configurations to alternate file
  95. $ cp /Library/Preferences/SystemConfiguration/com.apple.Boot.plist /next_boot.plist
  96. 3. Update the kernelcache and boot-args for your setup
  97. $ plutil -insert "Kernel Cache" -string "kernelcache.test" /next_boot.plist
  98. $ plutil -replace "Kernel Flags" -string "debug=0x144 -v kernelsuffix=test " /next_boot.plist
  99. 4. Copy the new config to `/Library/Preferences/SystemConfiguration/`
  100. $ cp /next_boot.plist /Library/Preferences/SystemConfiguration/boot.plist
  101. 5. Bless the volume with new configs.
  102. $ sudo -n bless --mount / --setBoot --nextonly --options "config=boot"
  103. The `--nextonly` flag specifies that use the `boot.plist` configs only for one boot.
  104. So if the kernel panic's you can easily power reboot and recover back to original kernel.
  105. Creating tags and cscope
  106. ========================
  107. Set up your build environment and from the top directory, run:
  108. $ make tags # this will build ctags and etags on a case-sensitive volume, only ctags on case-insensitive
  109. $ make TAGS # this will build etags
  110. $ make cscope # this will build cscope database
  111. How to install a new header file from XNU
  112. =========================================
  113. To install IOKit headers, see additional comments in [iokit/IOKit/Makefile]().
  114. XNU installs header files at the following locations -
  115. a. $(DSTROOT)/System/Library/Frameworks/Kernel.framework/Headers
  116. b. $(DSTROOT)/System/Library/Frameworks/Kernel.framework/PrivateHeaders
  117. c. $(DSTROOT)/usr/include/
  118. d. $(DSTROOT)/usr/local/include/
  119. e. $(DSTROOT)/System/DriverKit/usr/include/
  120. f. $(DSTROOT)/System/Library/Frameworks/System.framework/PrivateHeaders
  121. `Kernel.framework` is used by kernel extensions.\
  122. The `System.framework`, `/usr/include` and `/usr/local/include` are used by user level applications. \
  123. `/System/DriverKit/usr/include` is used by userspace drivers. \
  124. The header files in framework's `PrivateHeaders` are only available for ** Apple Internal Development **.
  125. The directory containing the header file should have a Makefile that
  126. creates the list of files that should be installed at different locations.
  127. If you are adding the first header file in a directory, you will need to
  128. create Makefile similar to `xnu/bsd/sys/Makefile`.
  129. Add your header file to the correct file list depending on where you want
  130. to install it. The default locations where the header files are installed
  131. from each file list are -
  132. a. `DATAFILES` : To make header file available in user level -
  133. `$(DSTROOT)/usr/include`
  134. `$(DSTROOT)/System/Library/Frameworks/System.framework/PrivateHeaders`
  135. b. `DRIVERKIT_DATAFILES` : To make header file available to DriverKit userspace drivers -
  136. `$(DSTROOT)/System/DriverKit/usr/include`
  137. c. `PRIVATE_DATAFILES` : To make header file available to Apple internal in
  138. user level -
  139. `$(DSTROOT)/System/Library/Frameworks/System.framework/PrivateHeaders`
  140. d. `EMBEDDED_PRIVATE_DATAFILES` : To make header file available in user
  141. level for macOS as `EXTRA_DATAFILES`, but Apple internal in user level
  142. for embedded OSes as `EXTRA_PRIVATE_DATAFILES` -
  143. `$(DSTROOT)/usr/include` (`EXTRA_DATAFILES`)
  144. `$(DSTROOT)/usr/local/include` (`EXTRA_PRIVATE_DATAFILES`)
  145. d. `KERNELFILES` : To make header file available in kernel level -
  146. `$(DSTROOT)/System/Library/Frameworks/Kernel.framework/Headers`
  147. `$(DSTROOT)/System/Library/Frameworks/Kernel.framework/PrivateHeaders`
  148. e. `PRIVATE_KERNELFILES` : To make header file available to Apple internal
  149. for kernel extensions -
  150. `$(DSTROOT)/System/Library/Frameworks/Kernel.framework/PrivateHeaders`
  151. f. `MODULEMAPFILES` : To make module map file available in user level -
  152. `$(DSTROOT)/usr/include`
  153. g. `PRIVATE_MODULEMAPFILES` : To make module map file available to Apple
  154. internal in user level -
  155. `$(DSTROOT)/usr/local/include`
  156. The Makefile combines the file lists mentioned above into different
  157. install lists which are used by build system to install the header files. There
  158. are two types of install lists: machine-dependent and machine-independent.
  159. These lists are indicated by the presence of `MD` and `MI` in the build
  160. setting, respectively. If your header is architecture-specific, then you should
  161. use a machine-dependent install list (e.g. `INSTALL_MD_LIST`). If your header
  162. should be installed for all architectures, then you should use a
  163. machine-independent install list (e.g. `INSTALL_MI_LIST`).
  164. If the install list that you are interested does not exist, create it
  165. by adding the appropriate file lists. The default install lists, its
  166. member file lists and their default location are described below -
  167. a. `INSTALL_MI_LIST`, `INSTALL_MODULEMAP_MI_LIST` : Installs header and module map
  168. files to a location that is available to everyone in user level.
  169. Locations -
  170. $(DSTROOT)/usr/include
  171. Definition -
  172. INSTALL_MI_LIST = ${DATAFILES}
  173. INSTALL_MODULEMAP_MI_LIST = ${MODULEMAPFILES}
  174. b. `INSTALL_DRIVERKIT_MI_LIST` : Installs header file to a location that is
  175. available to DriverKit userspace drivers.
  176. Locations -
  177. $(DSTROOT)/System/DriverKit/usr/include
  178. Definition -
  179. INSTALL_DRIVERKIT_MI_LIST = ${DRIVERKIT_DATAFILES}
  180. c. `INSTALL_MI_LCL_LIST`, `INSTALL_MODULEMAP_MI_LCL_LIST` : Installs header and
  181. module map files to a location that is available for Apple internal in user level.
  182. Locations -
  183. $(DSTROOT)/usr/local/include
  184. Definition -
  185. INSTALL_MI_LCL_LIST =
  186. INSTALL_MODULEMAP_MI_LCL_LIST = ${PRIVATE_MODULEMAPFILES}
  187. d. `INSTALL_SF_MI_LCL_LIST` : Installs header file to a location that is available
  188. for Apple internal in user level.
  189. Locations -
  190. $(DSTROOT)/System/Library/Frameworks/System.framework/PrivateHeaders
  191. Definition -
  192. INSTALL_SF_MI_LCL_LIST = ${DATAFILES} ${PRIVATE_DATAFILES}
  193. e. `INSTALL_KF_MI_LIST` : Installs header file to location that is available
  194. to everyone for kernel extensions.
  195. Locations -
  196. $(DSTROOT)/System/Library/Frameworks/Kernel.framework/Headers
  197. Definition -
  198. INSTALL_KF_MI_LIST = ${KERNELFILES}
  199. f. `INSTALL_KF_MI_LCL_LIST` : Installs header file to location that is
  200. available for Apple internal for kernel extensions.
  201. Locations -
  202. $(DSTROOT)/System/Library/Frameworks/Kernel.framework/PrivateHeaders
  203. Definition -
  204. INSTALL_KF_MI_LCL_LIST = ${KERNELFILES} ${PRIVATE_KERNELFILES}
  205. g. `EXPORT_MI_LIST` : Exports header file to all of xnu (bsd/, osfmk/, etc.)
  206. for compilation only. Does not install anything into the SDK.
  207. Definition -
  208. EXPORT_MI_LIST = ${KERNELFILES} ${PRIVATE_KERNELFILES}
  209. If you want to install the header file in a sub-directory of the paths
  210. described in (1), specify the directory name using two variables
  211. `INSTALL_MI_DIR` and `EXPORT_MI_DIR` as follows -
  212. INSTALL_MI_DIR = dirname
  213. EXPORT_MI_DIR = dirname
  214. If you want to install the module map file in a sub-directory, specify the
  215. directory name using the variable `INSTALL_MODULEMAP_MI_DIR` as follows -
  216. INSTALL_MODULEMAP_MI_DIR = dirname
  217. A single header file can exist at different locations using the steps
  218. mentioned above. However it might not be desirable to make all the code
  219. in the header file available at all the locations. For example, you
  220. want to export a function only to kernel level but not user level.
  221. You can use C language's pre-processor directive (#ifdef, #endif, #ifndef)
  222. to control the text generated before a header file is installed. The kernel
  223. only includes the code if the conditional macro is TRUE and strips out
  224. code for FALSE conditions from the header file.
  225. Some pre-defined macros and their descriptions are -
  226. a. `PRIVATE` : If defined, enclosed definitions are considered System
  227. Private Interfaces. These are visible within xnu and
  228. exposed in user/kernel headers installed within the AppleInternal
  229. "PrivateHeaders" sections of the System and Kernel frameworks.
  230. b. `KERNEL_PRIVATE` : If defined, enclosed code is available to all of xnu
  231. kernel and Apple internal kernel extensions and omitted from user
  232. headers.
  233. c. `BSD_KERNEL_PRIVATE` : If defined, enclosed code is visible exclusively
  234. within the xnu/bsd module.
  235. d. `MACH_KERNEL_PRIVATE`: If defined, enclosed code is visible exclusively
  236. within the xnu/osfmk module.
  237. e. `XNU_KERNEL_PRIVATE`: If defined, enclosed code is visible exclusively
  238. within xnu.
  239. f. `KERNEL` : If defined, enclosed code is available within xnu and kernel
  240. extensions and is not visible in user level header files. Only the
  241. header files installed in following paths will have the code -
  242. $(DSTROOT)/System/Library/Frameworks/Kernel.framework/Headers
  243. $(DSTROOT)/System/Library/Frameworks/Kernel.framework/PrivateHeaders
  244. g. `DRIVERKIT`: If defined, enclosed code is visible exclusively in the
  245. DriverKit SDK headers used by userspace drivers.
  246. Module map file name convention
  247. ===============================
  248. In the simple case, a subdirectory of `usr/include` or `usr/local/include`
  249. can be represented by a standalone module. Where this is the case, set
  250. `INSTALL_MODULEMAP_MI_DIR` to `INSTALL_MI_DIR` and install a `module.modulemap`
  251. file there. `module.modulemap` is used even for private modules in
  252. `usr/local/include`; `module.private.modulemap` is not used. Caveat: in order
  253. to stay in the simple case, the module name needs to be exactly the same as
  254. the directory name. If that's not possible, then the following method will
  255. need to be applied.
  256. `xnu` contributes to the modules defined in CoreOSModuleMaps by installing
  257. module map files that are sourced from `usr/include/module.modulemap` and
  258. `usr/local/include/module.modulemap`. The naming convention for the `xnu`
  259. module map files are as follows.
  260. a. Ideally the module map file covers an entire directory. A module map
  261. file covering `usr/include/a/b/c` would be named `a_b_c.modulemap`.
  262. `usr/local/include/a/b/c` would be `a_b_c_private.modulemap`.
  263. b. Some headers are special and require their own module. In that case,
  264. the module map file would be named after the module it defines.
  265. A module map file defining the module `One.Two.Three` would be named
  266. `one_two_three.modulemap`.
  267. Conditional compilation
  268. =======================
  269. `xnu` offers the following mechanisms for conditionally compiling code:
  270. a. *CPU Characteristics* If the code you are guarding has specific
  271. characterstics that will vary only based on the CPU architecture being
  272. targeted, use this option. Prefer checking for features of the
  273. architecture (e.g. `__LP64__`, `__LITTLE_ENDIAN__`, etc.).
  274. b. *New Features* If the code you are guarding, when taken together,
  275. implements a feature, you should define a new feature in `config/MASTER`
  276. and use the resulting `CONFIG` preprocessor token (e.g. for a feature
  277. named `config_virtual_memory`, check for `#if CONFIG_VIRTUAL_MEMORY`).
  278. This practice ensures that existing features may be brought to other
  279. platforms by simply changing a feature switch.
  280. c. *Existing Features* You can use existing features if your code is
  281. strongly tied to them (e.g. use `SECURE_KERNEL` if your code implements
  282. new functionality that is exclusively relevant to the trusted kernel and
  283. updates the definition/understanding of what being a trusted kernel means).
  284. It is recommended that you avoid compiling based on the target platform. `xnu`
  285. does not define the platform macros from `TargetConditionals.h`
  286. (`TARGET_OS_OSX`, `TARGET_OS_IOS`, etc.).
  287. Debugging xnu
  288. =============
  289. By default, the kernel reboots in the event of a panic.
  290. This behavior can be overriden by the `debug` boot-arg -- `debug=0x14e` will cause a panic to wait for a debugger to attach.
  291. To boot a kernel so it can be debugged by an attached machine, override the `kdp_match_name` boot-arg with the appropriate `ifconfig` interface.
  292. Ethernet, Thunderbolt, and serial debugging are supported, depending on the hardware.
  293. Use LLDB to debug the kernel:
  294. ; xcrun -sdk macosx lldb <path-to-unstripped-kernel>
  295. (lldb) gdb-remote [<host-ip>:]<port>
  296. The debug info for the kernel (dSYM) comes with a set of macros to support kernel debugging.
  297. To load these macros automatically when attaching to the kernel, add the following to `~/.lldbinit`:
  298. settings set target.load-script-from-symbol-file true
  299. `tools/lldbmacros` contains the source for these commands.
  300. See the README in that directory for their usage, or use the built-in LLDB help with:
  301. (lldb) help showcurrentstacks

        通过阅读README.md,我们可以知道每个目录的作用。osfmk目录中是Mach层代码,它是系统最核心的部分,源码分析应该从这里开始。我们进入osfmk目录,其内容如下图所示:

        到这一级目录,我们发现没有README了,就只好猜一下这些子目录是干什么的。从名称看,kern和mach里应该有核心代码,machine里应该有操作硬件的代码,vm里应该有虚拟内存(内存管理)的代码,arm,arm64和x86_64里应该是机器相关的代码。

        目前,我们只关注x86_64架构下的XNU内核,暂时忽略arm架构。于是,我们进入x86_64子目录,内容如下:

        我们发现这里面有一堆.s的文件,这是汇编语言源代码。操作系统内核中,汇编语言用的地方不多,也就是启动代码和对性能要求高的代码用汇编写。我们发现有一个文件叫start.s,这就应该是启动代码了,之后将带大家分析。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/891267
推荐阅读
相关标签
  

闽ICP备14008679号