The ability to monitor child threads’ manipulation of the UI, or to add custom apis for monitoring (to capture specific stack information when child threads are monitoring certain apis to help locate problems)

background

For those of you who haven’t encountered a bunch of logs from the Xcode Console during development due to UI manipulation on child threads, it looks something like this

If Xcode has a Runtime Issue Breakpoint and type is Main Thread Checker, it will be detected when a child Thread is operating on the UI and trigger a Breakpoint. At the same time, you can see the stack

Results the following

Problems and solutions

The above functions are built-in in Xcode, which can only be provided by connecting Xcode for debugging, but cannot be detected by online packages.

After exploring the Xcode libMainThreadChecker on the realization of the function is dependent on the equipment. The dylib library, we can through the dlopen method to load the library enforcement not Xcode environment also has a monitoring function.

In the monitoring to the child thread calls the UI invoked, in Xcode environment, the call stack will be output to the console, tested, libMainThreadChecker. Dylib is used to output, because the NSLog is the information output to STDERR, We can intercept the STDERR output through NSPipe and dup2, and obtain the UI calls detected by judging the text of the information, which can be printed out through the stack to help locate the specific problem.

LibMainThreadChecker dylib library has limitations, only to some of the specific class specific apis provided by the system in the child thread calls will be monitored to (for example, the UIKit framework UIView class). But some kind of some apis we also don’t want a child thread is invoked, this time libMainThreadChecker. Dylib is unable to satisfy.

rightlibMainThreadChecker.dylibLibrary of assembly code research, foundlibMainThreadChecker.dylibIs through the inside__main_thread_add_check_for_selectorThis method is used to register classes and methods. So if we can also get throughdlsymTo monitor the main thread calls to custom classes and methods.

In addition, this function can be enabled in the offline debug phase. You can use the official verification method provided by Apple to check whether Xcode debug is enabled.

If you are unfamiliar with Dlopen and DLSYm, you can read the official Apple documentation directly.

APM collection

If you are interested in APM, you can check out this article about how to build an APM monitoring system