OS X: Do sections in the __TEXT segment get modified by other programs?
Does it happen that some program (or even the OS itself) changes the contents of an executable's __TEXT segment, for whatever reason?
- Note: Here, I'm referring to the "__TEXT" segment, not the "__text" section.
In other words: can I rely on bytes in the __TEXT segment of 开发者_开发技巧my executable to detect whether my executable has been damaged (say by computing a checksum on that segment), or is there a chance I get false positives because this segment may be modified after the program has been installed on the user's computer?
Thanks!
Segments are essentially a virtual memory construct: they're typically aligned on page boundaries, so they may end up including a bit more than your application's code. Given the __TEXT
segment usually starts at the beginning of a Mach-O file, this generally includes the Mach-O headers, too.
In OS X 10.3 and earlier, prebinding could affect the __TEXT
segment (which is described in detail here). In later versions, code signing can also modify the __TEXT
segment.
You may want to investigate using OS X's built-in code-signing mechanism (the cause of, and solution to, your problem?). Some recommended references:
- Technical Note TN2206: Mac OS X Code Signing In Depth
- Code Signing and You (ignore the iPhone bits)
- Development Phase Code Signing
You may find macholib useful in exploring. (It's included with recent OS X versions to support py2app.) Here's a simple script I used to extract a __TEXT
segment.
from macholib.MachO import MachO
m = MachO('foo')
__TEXT = (cmd for load_cmd, cmd, data in m.headers[0].commands
if getattr(cmd, 'segname', '').rstrip('\0') == '__TEXT').next()
print '__TEXT segment: offset %x size %x' % (__TEXT.fileoff, __TEXT.filesize)
f = open('foo', 'rb')
f.seek(__TEXT.fileoff)
open('foo__TEXT', 'wb').write(f.read(__TEXT.filesize))
Of course, you can also use otool -lv
, but the output is a bit messy and hard to parse.
精彩评论