convert MH_EXECUTE to MH_DYLIB (mach-o) - ios

The problem:
I have 2 MH_EXECUTE iOS binary files (compiled, no source code).
Lets name them binary1 and binary2.
I try to switch between them before UIApplicationMain is called!
1 try
I successfully do this with binary1 and one dylib. So I try to convert MH_EXECUTE to MH_DYLIB.
step 1
creating iOS Application binary1
#import <dlfcn.h>
int main(int argc, char * argv[])
{
NSLog(#"binary1 -> Hello, World!");
void *handle = dlopen([[[NSBundle mainBundle] pathForResource:#"binary2" ofType:nil] cStringUsingEncoding:NSUTF8StringEncoding], RTLD_NOW);
if (handle)
{
NSLog(#"DLOPEN is OK!");
}
else
{
NSLog(#"!OK ... --> %s", dlerror());
}
return 0;
}
creating iOS Application binary2
int main(int argc, char * argv[])
{
NSLog(#"binary2 -> Hello, World!");
return 0;
}
When I run binary1 I get:
step 2
Lets see the difference MH_EXECUTE vs MH_DYLIB
fullscreen
as we can see the main difference here is File Type: MH_EXECUTE vs MH_DYLIB
Lets change them and run binary1 again.
After change the result was out of address space
step 3
Lets see Load Commands
fullscreen
* in dylib there is NO __PAGEZERO segment
* dylib __TEXT segment VM address == 0 but in binary2 == 0000000100000000
So lets patch them too ... (patched: __TEXT, ___DATA and __LINKEDIT)
After run binary1 i get malformed mach-o image: segment __PAGEZERO overlaps load commands
step 4
I successfully removed __PAGEZERO from Load Commands now binary looks like dylib:
fullscreen
But on start binary1 I get BAD_ACCESS
Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Subtype: KERN_PROTECTION_FAILURE at 0x00000001019e0010
Triggered by Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 dyld 0x0000000120016d78 ImageLoaderMachOCompressed::rebase(ImageLoader::LinkContext const&) + 892
1 dyld 0x0000000120016c24 ImageLoaderMachOCompressed::rebase(ImageLoader::LinkContext const&) + 552
2 dyld 0x0000000120010c8c ImageLoader::recursiveRebase(ImageLoader::LinkContext const&) + 132
3 dyld 0x000000012001039c ImageLoader::link(ImageLoader::LinkContext const&, bool, bool, bool, ImageLoader::RPathChain const&) + 176
4 dyld 0x00000001200088e0 dyld::link(ImageLoader*, bool, bool, ImageLoader::RPathChain const&) + 180
5 dyld 0x000000012000df68 dlopen + 684
6 libdyld.dylib 0x0000000194e65b94 dlopen + 68
7 binary1 0x00000001000b7e18 main (main.m:16)
8 libdyld.dylib 0x0000000194e66a04 start + 0
Any idea ???

You're getting BAD_ACCESS because you removed __PAGEZERO and thus invalidated the rebasing opcodes. Keep __PAGEZERO but nullify it. I similarly converted an executable into a shared library and it's loading fine on iOS and macOS.

Related

Crash on one specific Unity scene in iOS build - TexturesMetal::AddCreatedTexture

I am having a crash only on one specific scene in my AR Foundation Unity build with the following error.
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000020
VM Region Info: 0x20 is not in any region. Bytes before following region: 4362387424
REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL
UNUSED SPACE AT START
__TEXT 10404c000-104050000 [ 16K] r-x/r-x SM=COW ...lycoroTestApp
Termination Signal: Segmentation fault: 11
Termination Reason: Namespace SIGNAL, Code 0xb
Terminating Process: exc handler [5380]
Triggered by Thread: 28
Thread 28 name:
Thread 28 Crashed:
0 libobjc.A.dylib 0x0000000195ac5ac0 objc_retain + 16 (objc-object.h:636)
1 UnityFramework 0x00000001066d5320 TexturesMetal::AddCreatedTexture(TextureID, id, bool) + 32 (TexturesMetal.mm:481)
2 UnityFramework 0x0000000106634828 GfxDeviceWorker::RunCommand(ThreadedStreamBuffer&) + 21972 (GfxDeviceWorker.cpp:0)
3 UnityFramework 0x00000001066aa2ec GfxDeviceWorkerAutoreleasePoolProxy + 68 (GfxDeviceMetal.mm:5242)
4 UnityFramework 0x0000000106636bd0 GfxDeviceWorker::RunExt(ThreadedStreamBuffer&) + 92 (GfxDeviceWorker.cpp:389)
5 UnityFramework 0x0000000106636b68 GfxDeviceWorker::Run() + 156 (GfxDeviceWorker.cpp:373)
6 UnityFramework 0x000000010662ef70 GfxDeviceWorker::RunGfxDeviceWorker(void*) + 12 (GfxDeviceWorker.cpp:352)
7 UnityFramework 0x00000001062289f8 Thread::RunThreadWrapper(void*) + 496 (Thread.cpp:81)
8 libsystem_pthread.dylib 0x00000001c9777c74 _pthread_start + 288 (pthread.c:887)
9 libsystem_pthread.dylib 0x00000001c977c878 thread_start + 8
At first I thought it was because I was missing the Environmental Probe manager in that scene (no). Then I thought perhaps it was because I was using a specific shader that didn't use a _MainTex. But I use that shader no problem in other working scenes.
And then I built the scene with only a simple primitive and my UI and still received this error. After that crash the scene did open successfully, but obviously the problem is still there. The UI is the exact same as the other working scenes.
I can't find out much about this specific error: TexturesMetal::AddCreatedTexture - only that there may be this bug with GLES3 and PVRTC textures - but they aren't present in the most recent build.
https://issuetracker.unity3d.com/issues/ios-crash-in-uploadtexture-at-texturesmeta-dot-mm-or-drawbufferranges-at-gfxdevicegles-dot-cpp-using-atlas-with-pvrtc-compress
The scene works perfectly in Android - it only crashes in iOS.
Any ideas? Full report below.
I ran a Product>Analysis in Xcode and it gave me this warning:
/Users/xcodeclub/Downloads/Eliot Silver/Classes/UI/UnityView.mm:200:5: nil returned from a method that is expected to return a non-null value
For this bit of Code in UnityView.mm:
static Class UnityRenderingView_LayerClassMTL(id self_, SEL _cmd)
{
return NSClassFromString(#"CAMetalLayer");
}
static Class UnityRenderingView_LayerClassNULL(id self_, SEL _cmd)
{
return NSClassFromString(#"CALayer");
}
#implementation UnityRenderingView
(Class)layerClass
{
return nil;
}
(void)InitializeForAPI:(UnityRenderingAPI)api
{
IMP layerClassImpl = api == apiMetal ? (IMP)UnityRenderingView_LayerClassMTL : (IMP)UnityRenderingView_LayerClassNULL;
class_replaceMethod(object_getClass([UnityRenderingView class]), #Selector(layerClass), layerClassImpl, UIView_LayerClass_Enc);
}
#End

Google Nearby Messages Crashed: AudioRecorderCallbackQueue on deallocation

I'm using Swift to use Google Nearby Messages library. I followed the sample code to setup the library. I'm using both bluetooth and microphone to test the function. I dealloc the publication/subscription in viewDidDisappear(). Basically it's two lines of code:
publication = nil
subscription = nil
However, when I dismiss the view controller, sometimes the whole app will crash. The stacktrace only shows that the crash has something to do with the audio. Here's part of the stacktrace:
Crashed: AudioRecorderCallbackQueue
0 libdispatch.dylib 0x18df39f60 _dispatch_barrier_sync_f_slow + 596
1 ProjectLibs 0x1037ad8e0 std::__1::vector<unsigned char, std::__1::allocator<unsigned char> >::vector(std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&) + 2808
2 ProjectLibs 0x1037ad8e0 std::__1::vector<unsigned char, std::__1::allocator<unsigned char> >::vector(std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&) + 2808
3 ProjectLibs 0x1037ad0f4 std::__1::vector<unsigned char, std::__1::allocator<unsigned char> >::vector(std::__1::vector<unsigned char, std::__1::allocator<unsigned char> > const&) + 780
4 libsystem_blocks.dylib 0x18df7ea28 _Block_release + 144
Does anyone have any idea what may have caused the crash, and how to solve it or prevent the app from crash?
Thanks!
I set up an app to behave the way you have described yours as working. By enabling the logging, I notice that it is still sending messages for a brief period of time, which is likely where your crash is coming from.
You can enable logging with this command:
GNSMessageManager.setDebugLoggingEnabled(true)
By setting them to nil earlier in the process, I was able to get them to stop being sent before the viewcontroller was completely closed down.
The following does it at the soonest point possible (even before viewWillDisappear):
override func willMove(toParentViewController parent: UIViewController?) {
super.willMove(toParentViewController: parent)
if parent == nil {
publication = nil
subscription = nil
}
}

Segfault from NSLog?

I'm seeing a segfault from using NSLog and specifically, it is on a 64 bit device, with a SEGV_ACCERR. I'm new to iOS, so i'm a little confused.
Here's the stack trace:
Exception Type: SIGSEGV
Exception Codes: SEGV_ACCERR at 0x108074000
Crashed Thread: 0
Thread 0 Crashed:
0 libsystem_platform.dylib 0x00000001826ea31c _platform_memmove + 300
1 libsystem_asl.dylib 0x00000001825289a4 asl_string_append_no_encoding_len + 92
2 libsystem_asl.dylib 0x0000000182522fc8 asl_string_new + 108
3 libsystem_asl.dylib 0x0000000182522df4 asl_msg_to_string_raw + 68
4 libsystem_asl.dylib 0x00000001825228dc _asl_send_message + 828
5 libsystem_asl.dylib 0x00000001825224fc asl_send + 8
6 CoreFoundation 0x0000000182a6fa1c __CFLogCString + 568
7 CoreFoundation 0x0000000182a6f7ac _CFLogvEx2 + 300
8 CoreFoundation 0x0000000182a6fc14 _CFLogvEx3 + 152
9 Foundation 0x0000000183435dd8 _NSLogv + 128
10 Foundation 0x000000018336ae04 NSLog + 28
Here is the code that calls this:
NSString *truncated = [NSString stringWithUTF8String:buffer];
// Using original NSLog to print.
#undef NSLog
NSLog(#"%#", truncated);
and it crashes from my NSLog call.
where buffer is just a char buffer.
My questions specifically are:
Is it even possible to crash from using Apple's provided NSLog? Or is my stack trace wrong?
What does SEG_ACCERR even mean in this context?
How could i go about finding if this was caused by a bad memory issue or not?
Is something blowing up with the asl file under multiple threads?
How should i approach debugging this?
Any help would be greatly appreciated! Thanks!
You say that buffer is a char buffer. If that is the case, you should initialize the string like this
NSString *truncated = [[NSString alloc] initWithBytes:buffer
length:len NSUTF8StringEncoding];
where len is the length of the characters in the buffer.

Swift compiler segmentation fault with generic recursive function

I've run into an interesting issue with the Swift compiler, which seems to be caused by a very simple generic function. I've got a workaround, but I'd really like to understand what the underlying issue is.
In my app I have a requirement to fade in some UICollectionViewCells in a given order, sequentially, with a slight overlap between the animations.
I've implemented this using the methods below. The revealCells method takes an array of cells. If the collection is empty, it simply returns. Otherwise it animates the fade-in on the first cell in the array, and then waits a certain amount of time before making a recursive call to itself, passing all the cells except the one it just animated.
Code below:
func revealCells(cells:[UICollectionViewCell],animationTime:NSTimeInterval,overlap:Double) {
if cells.count > 0 {
let firstCell = cells.first
UIView.animateWithDuration(0.3, animations: { () -> Void in
firstCell?.alpha = 1.0
let timeMinusOverlap = animationTime - overlap
let delayTime = dispatch_time(DISPATCH_TIME_NOW,Int64(timeMinusOverlap * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue(), { () -> Void in
self.revealCells(self.cdr(cells),animationTime: animationTime,overlap: overlap)
})
})
}
}
}
//Returns the collection passed into the function with its first element removed
//i.e the traditional LISP cdr function
func cdr<T>(input:[T]) -> [T] {
var rVal = [T]()
if input.count == 1 {
rVal.append(input.first!)
} else {
rVal = [T](input[1...input.count-1])
}
return rVal
}
All this works fine in the simulator. But when I try to archive the build, the swift compiler crashes with the message Swift Compiler Error Command failed due to signal: Segmentation fault 11. My setup is Xcode 6.3.1 (iOSSDK 8.3), and my min deployment target is 8.3.
Fixing the problem is trivial - if I just replace the code inside the dispatch_after with:
let newCells = [UICollectionViewCell](cells[1...cells.count-1])
self.revealCells(newCells,animationTime: animationTime,overlap: overlap)
the problem goes away. So it seems to be something to do with the generic function, or possibly something block related.
Stack trace is:
0 swift 0x000000010105ba18 llvm::sys::PrintStackTrace(__sFILE*) + 40
1 swift 0x000000010105bef4 SignalHandler(int) + 452
2 libsystem_platform.dylib 0x00007fff8725ef1a _sigtramp + 26
3 libsystem_platform.dylib 0x000000000000000f _sigtramp + 2027557135
4 swift 0x00000001021a98cb llvm::AsmPrinter::EmitFunctionBody() + 4379
5 swift 0x000000010116c84c llvm::ARMAsmPrinter::runOnMachineFunction(llvm::MachineFunction&) + 220
6 swift 0x0000000100d81d13 llvm::MachineFunctionPass::runOnFunction(llvm::Function&) + 99
7 swift 0x00000001024d5edf llvm::FPPassManager::runOnFunction(llvm::Function&) + 495
8 swift 0x00000001024d60cb llvm::FPPassManager::runOnModule(llvm::Module&) + 43
9 swift 0x00000001024d658f llvm::legacy::PassManagerImpl::run(llvm::Module&) + 975
10 swift 0x0000000100a09b41 performIRGeneration(swift::IRGenOptions&, swift::Module*, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, swift::SourceFile*, unsigned int) + 4369
11 swift 0x0000000100a09cb3 swift::performIRGeneration(swift::IRGenOptions&, swift::SourceFile&, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, unsigned int) + 51
12 swift 0x0000000100945687 frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 6647
13 swift 0x0000000100943ae6 main + 1814
14 libdyld.dylib 0x00007fff8a46b5c9 start + 1
(a long list of program arguments, which are mostly the names of file being compiled)
1. Running pass 'Function Pass Manager' on module '/Users/tolleyr/Library/Developer/Xcode/DerivedData/ParseTestQuiz-fgnfjkxxlyqfnrfrfntgtsjnrcfv/Build/Intermediates/ArchiveIntermediates/ParseTestQuiz/IntermediateBuildFilesPath/ParseTestQuiz.build/Release-iphoneos/ParseTestQuiz.build/Objects-normal/armv7/QuizQuestionViewController.o'.
2. Running pass 'ARM Assembly / Object Emitter' on function '#_TFC13ParseTestQuiz26QuizQuestionViewController13viewDidAppearfS0_FSbT_'
(the last part enabled me to figure out what code was causing the problem). The command being run was CompileSwift normal armv7
I'm going to file a radar for this, since the compiler itself is crashing , but thought I'd post it here in case anyone has an idea of what might be going on, or has run into the same issue.

Segmentation Fault: 11 - Xcode 6.3

Can't archive
My app runs fine (Xcode 6.3.2, swift based) on Simulator and on multiple devices. But when I try to archive it I get the error Command failed due to signal: Segmentation fault: 11.
Others face same problem
Segmentation Fault 11 when running Swift app
"Command failed due to signal: Segmentation fault: 11" - What is the issue?
Command failed due to signal: Segmentation fault: 11
Root cause?
But it seems that each have different reasons for getting the error.. I am unable to comprehend the error message I am getting. Posted below, any hints or tips would be greatly appreciated!
Error log
0 swift 0x0000000108e5d2b8 llvm::sys::PrintStackTrace(__sFILE*) + 40
1 swift 0x0000000108e5d794 SignalHandler(int) + 452
2 libsystem_platform.dylib 0x00007fff8897bf1a _sigtramp + 26
3 libsystem_platform.dylib 0x00007fff574b7b28 _sigtramp + 3467885608
4 swift 0x0000000108a053f2 swift::serialization::Serializer::writeCrossReference(swift::Decl const*) + 578
5 swift 0x0000000108a0e275 swift::serialization::Serializer::writeAllDeclsAndTypes() + 2181
6 swift 0x0000000108a0f2f8 swift::serialization::Serializer::writeAST(llvm::PointerUnion<swift::Module*, swift::SourceFile*>) + 2600
7 swift 0x0000000108a11960 swift::serialization::Serializer::writeToStream(llvm::raw_ostream&, llvm::PointerUnion<swift::Module*, swift::SourceFile*>, swift::SILModule const*, swift::SerializationOptions const&) + 144
8 swift 0x0000000108a12521 swift::serialize(llvm::PointerUnion<swift::Module*, swift::SourceFile*>, swift::SerializationOptions const&, swift::SILModule const*) + 321
9 swift 0x0000000108746c1a frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 5514
10 swift 0x00000001087454e6 main + 1814
11 libdyld.dylib 0x00007fff8db235c9 start + 1
12 libdyld.dylib 0x0000000000000080 start + 1917700792
Solved it. Problem was two things:
1) Converting to Double
2) Handling an empty array
Converting to Double
Changed from var lat: Double? = d["lat"].doubleValue to var lat: Double? = Double(d["lat"].doubleValue)
Handling an empty array
Changed from
let brands = d["brands_unfiltered"].arrayValue {
if brands == [] {
// Do nothing (empty)
}
else{
// Do stuff
}
To
if let brands = d["brands_unfiltered"].arrayValue as Array! {
// Do stuff
}
To find the root cause I deactivated larges part of the code until I found what got the archiving not to function. Thereafter the solution was pretty straight forward. Hope this helps someone else struggling with the same error.
I found the code that cause my "Archive" action to fail with this error "Command failed due to signal: Segmentation fault: 11"
When I use the indexPath in the cellForRowAtIndexPath function, I need to put an exclamation mark (i.e indexPath! instead of indexPath). However, I still puzzled by why there is such error if I omit the exclamation mark. Does anyone know the reason?
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!, object: PFObject!) -> PFTableViewCell! {
// code to get cell, etc
let thumbnailImage = self.userPhotos?.getFromCacheOrDownload(username,
circle: team.circle(), delegate: self, indexPath: indexPath!)
cell.userPhotoImageView.image = thumbnailImage
return cell
}

Resources