Detecting Unused Code in Mixed Swift and Objective‑C iOS Projects via Mach‑O Analysis
This article explains how to detect and remove unused code in mixed Swift and Objective‑C iOS applications by parsing Mach‑O files, analyzing class metadata, and leveraging AccessFunction calls, while discussing the challenges, implementation details of the WBBlades tool, and practical usage steps.
The article introduces a method for detecting unused code in mixed Swift and Objective‑C iOS projects by parsing Mach‑O files and applying disassembly techniques, focusing on Swift detection strategies.
It explains why unused code detection is important for binary size and startup performance, especially as Swift adoption grows within large apps, and describes the limitations of static detection that only provides a candidate set of dead code.
Traditional Objective‑C detection relies on the difference between classlist and classrefs , but this does not work for Swift because Swift classes are not recorded in classrefs unless they are exported to Objective‑C. The article shows example Objective‑C code and Swift code illustrating this difference.
To identify used Swift classes, the article details how the Swift ClassContextDescriptor and SwiftMetadataClass structures are stored in the __TEXT,__const section, and how the AccessFunction pointer in the descriptor is invoked at runtime. By locating AccessFunction calls in disassembled code, one can infer class usage.
The process of determining function instruction ranges using the symbol table ( struct nlist_64 ) is described, including sorting symbols by address and using the next symbol's address as the function's end.
Several practical challenges encountered while adapting the WBBlades tool for Swift are listed, such as inaccurate section detection, parent‑type traversal exceptions, complex generic layouts, anonymous context descriptors, and handling of demangling cache symbols.
The article provides a step‑by‑step guide for using WBBlades: build the tool, run it on a debug arm64 iOS binary with the -unused flag, and wait for the result file.
Results from the 58.com app show that about 8% of Objective‑C code and 2% of Swift code are dead, with an overall detection accuracy of over 80% for most business lines, while dynamic class name construction and Swift reflection remain difficult cases.
Finally, the author notes ongoing improvements to WBBlades, invites community contributions, and lists references to Apple documentation and related projects.
58 Tech
Official tech channel of 58, a platform for tech innovation, sharing, and communication.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.