macos 是否可以在 Mac OS 上挂钩 API 调用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2689348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 06:54:07  来源:igfitidea点击:

Is it possible to hook API calls on Mac OS?

macos

提问by mpipe3

On Windows there a few libraries that allow you to intercept calls to DLLs:

在 Windows 上,有一些库允许您拦截对 DLL 的调用:

http://www.codeproject.com/kb/system/hooksys.aspx

http://www.codeproject.com/kb/system/hooksys.aspx

Is it possible to do this on Mac OS? If so, how is it done?

是否可以在 Mac OS 上执行此操作?如果是这样,它是如何完成的?

回答by Nicholas Riley

The answer depends on whether you want to do this in your own application or systemwide. In your own application, it's pretty easy; the dynamic linker provides features such as DYLD_INSERT_LIBRARIES. If you're doing this for debugging/instrumentation purposes, also check out DTrace.

答案取决于您是要在自己的应用程序中还是在系统范围内执行此操作。在您自己的应用程序中,这很容易;动态链接器提供诸如DYLD_INSERT_LIBRARIES. 如果您这样做是为了调试/检测目的,还请查看 DTrace。

You can replace Objective-C method implementations with method swizzling, e.g. JRSwizzleor Apple's method_exchangeImplementations(10.5+).

您可以使用方法swizzling替换 Objective-C 方法实现,例如JRSwizzle或 Apple 的method_exchangeImplementations(10.5+)。

If you want to modify library behavior systemwide, you're going to need to load into other processes' address spaces.

如果您想在系统范围内修改库行为,您将需要加载到其他进程的地址空间。

  • Two loading mechanisms originally designed for other purposes (input managersand scripting additions) are commonly abused for this purpose, but I wouldn't really recommend them.
  • mach_inject/mach_overrideare an open-source set of libraries for loading code and replacing function implementations, respectively; however, you're responsible for writing your own application which uses the libraries. (Also, take a look at this answer; you need special permissions to inject code into other processes.)
  • 最初为其他目的设计的两种加载机制(输入管理器脚本添加)通常被滥用于此目的,但我不会真正推荐它们。
  • mach_inject/mach_override是一组开源的库,分别用于加载代码和替换函数实现;但是,您有责任编写自己的使用这些库的应用程序。(另外,看看这个答案;你需要特殊的权限才能将代码注入其他进程。)

Please keep in mind that application patching/code injection for non-debugging purposes is strongly discouraged by Apple and some Mac users (and developers) are extremely critical of the practice. Much of this criticism is poorly informed, but there have been a number of legitimately poorly written "plug-ins" (particularly those which patch Safari) that have been implicated in application crashes and problems. Code defensively.

请记住,Apple 强烈反对用于非调试目的的应用程序修补/代码注入,并且一些 Mac 用户(和开发人员)对这种做法极为挑剔。这种批评的大部分内容都不是很清楚,但有许多合法编写的“插件”(特别是那些修补 Safari 的插件)与应用程序崩溃和问题有关。防御性编码。

(Disclaimer: I am the author of a (free) APE module and an application which uses mach_inject.)

(免责声明:我是(免费)APE 模块和使用 的应用程序的作者mach_inject。)