如何从MachO二进制提取__bitcode段?llvm-objcopy操作失败排查
Alright, let's figure out why your llvm-objcopy commands were failing and how to properly get that __bitcode section out for use with opt or llvm-dis.
The Root of the Problem
Your confusion comes from how Mach-O files structure sections: every section belongs to a segment, and you were targeting the wrong segment in your commands. Looking at your objdump -h output, the __bitcode section is listed, but objdump doesn't show the parent segment name here. In reality, embedded bitcode sections in Mach-O files live in the __LLVM segment—not the __DATA segment you were trying to reference.
Step 1: Confirm the Segment-Section Pair
To get clear visibility of which segment the __bitcode section belongs to, use llvm-readobj (it's more verbose and precise for LLVM-related object files):
llvm-readobj -sections test.o
You'll see output like this for the __bitcode section:
Sections [ ... Section { Index: 3 Name: __bitcode SegmentName: __LLVM Address: 0x360 Size: 0x2bc0 Type: S_REGULAR (0x0) Attributes [ (0x0) ] Reserved1: 0x0 Reserved2: 0x0 } ... ]
This confirms the segment is __LLVM and the section is __bitcode.
Step 2: Correct llvm-objcopy Command
Now that you have the right segment-section pair, use this command to extract the bitcode:
llvm-objcopy --dump-section __LLVM,__bitcode=a.bc test.o
This tells llvm-objcopy to dump the __bitcode section from the __LLVM segment into a.bc.
Even Easier: Use extract-bc
LLVM has a dedicated tool for exactly this task—extract-bc—which automatically locates and extracts embedded bitcode without needing you to specify segment/section names. Just run:
extract-bc test.o
This will generate a test.bc file directly in your working directory.
Verify the Extracted Bitcode
To make sure you got a valid bitcode file, use llvm-dis to disassemble it into LLVM IR:
llvm-dis a.bc # Or test.bc if you used extract-bc
If this produces an a.ll (or test.ll) file with readable LLVM IR, you're good to go—this bitcode can now be used with opt for optimizations or any other LLVM tooling.
Why Your Previous Commands Failed
All your attempts referenced __DATA as the segment, but the __bitcode section isn't part of __DATA. Mach-O strictly enforces segment-section hierarchy, so specifying the wrong segment will always result in a "section not found" error.
内容的提问来源于stack exchange,提问作者A. K.

