I have a class, which is a boost serialization singleton. I need to do some initialization inside the main function of the program. So I made a public function in the singleton class, which I call in the main function.
Unfortunately the function somehow seems to never return, causing the remainder of the main function to not be executed... If I put a cout statement at the end of the called function, it does get printed, so nothing in the function itself is blocking.
I also found out that the singleton constructor is called before the main function is called.
I feel I'm missing something here.
Can somebody shed some light on this?
Thanks
The problem was, that boost::communicator must be called inside the main function:
boost::environment env(argc, argv);
There is a env definition which doesn't take arguments, but this didn't work in my case(don't know why).
Related
I have a function - myFunc() in class A. There are multiple other classes calling this function.
How will I be able to find out which class is calling myFunc() at a particular instance?
Would someone be able to help me with this?
Conceptually, this information is available in the stack, though it isn't easy to get to. Most solutions would involve creating an exception in order to capture the stack trace, and then reading the trace. I haven't tried this, but it might work:
void myFunc()
{
NSArray *stack = [NSThread callStackSymbols];
// I have no idea if the current function call is at the 0 or last position
// of the array. Experiment here!
}
Pertinent documentation: NSThread Class Reference
Note that if you want your function to behave differently depending on who is calling, DO NOT DO THIS. It's fragile (there are no guarantees about whether the format of what callStackSymbols returns will change).
It's better to simply pass a parameter into your function. If you're dealing with a C-function callback API, there is typically a void * "context" or "info" parameter that you can use to pass in an arbitrary pointer. This could be a pointer to your object.
Use the Visitor pattern
Have each of the calling classes implement a common protocol that defines the interface of the behavior you are looking to achieve.
Add the protocol as a parameter to myFunc.
When calling myFunc(), specify self as the parameter.
myFunc can now invoke any of the protocol methods without knowing about the other specific classes.
This way you adhere to the concepts of encapsulation.
When you call an method, for example, [objectA message:arg1 argument:arg2], what happens to the arguments?
For example, when you call a method, the address of that method is pushed to the call stack. But what happens to the arguments? Aren't they pushed to some stack too? Otherwise, how does the code of the method know where to find its arguments?
The reason I ask is because when you get a stack trace, you get the address of the functions or methods that have been called in order. When a method or function returns, the one that called it still has a reference to its own arguments. So there must me a reference to arg1 and arg2 somewhere. Therefore, from a stack trace and stack symbols on an iOS device, you must be able to get the method or function that called any other method or function, and also get its arguments.
How do you get these arguments?
On this other question: objective C log method call, they show a method to get the NSMethodSignature of a method and using that you can get the number and type of argument.
With that, an knowing where the arguments are located, you could get every function or method that has been called and the arguments that were used to call them.
Any help would be appreciated.
UPDATES
2011-08-03
In reply to "fakeAccount22" comments, I would like to do this at run-time from within the app.
My question basically boils down to: at run-time and within the app, how do you access the call stack or the stack pointer in Objective-C for an iOS device? Is it different for Mac OSX?
The key moment here is that when you invoke
[objectA message:arg1 argument:arg2]
you don't call method but you're sending message. Why? Cause in the end this line is translated by compiler into this:
objc_msgSend(objectA, "message:argument:", arg1, arg2)
That's all the magic. Everything else works as in C. Here is quite good explanation.
That's why all Objective C methods could be translated to their C-analogous (well, they are actually do translated). E.g. your example looks like this:
return_type method(id self, SEL _cmd, arg1_type arg1, arg2_type arg2) {
//implementation
}
Beside what Max wrote, the names and arguments of a method are known because the compiler generates a huge load of debug information, generated from the source code, and the debugger can use that to find names of methods and the names and values of their arguments, etc. This debug info is usually not easily available when you run your code without the debugger, although it ought to be accessible somehow, if you know the format how it is stored. But note that it can change with every new compilation.
Before a function call, the arguments get pushed on the call stack by the calling code, and when the call to the function is made, the return address is pushed there too, by the processor. Inside the function, the stack pointer is stored and now the stack can also be used to store local variables. At the end of the function, the original stack pointer is restored (which makes the local variables invalid and inaccessible) and the processor pops the return address and continues with the code after the call. The caller code than removes the arguments from the stack and continues with the rest of its code.
FWIW, that is how it happens in C. There are other, similar schemes, where items are pushed on the stack in a different order or even passed in registers, or where the function clears the arguments from the stack. Such a scheme is called a calling convention. Obj-C uses the cdecl calling convention, which is more or less how I described it.
If you write method implementations in Objective-C, it is pretty standard to sum up the methods of a class in the corresponding #interface blocks. Publically accessible methods go in the header file's interface, not-so-public methods can go in an empty category on top of the implementation file.
But it's not neccessary to declare an interface for every method. If you only reference the methods below their implementation code of the same class/file, there's no need to put any declaration anywhere else.
-(void) doSomething {
}
-(void) doSomethingElse {
[self doSomething];
}
Coming from another language, this is new to me. And I can't seem to decide whether it is nice and pretty to keep the interface blocks clean, or whether it should be prevented because the order of method implementations seem like a weird dependency to have.
What is the general public's opinion of this matter?
The general rule I follow is that if the only method calling doSomething is doSomethingElse then it's fine to not have doSomething be part of the declared private interface. But the moment a second method makes use of doSomething I add it to the declared interface.
The thinking behind this is that as long as the method is only ever called from one place there's no reason to think of it as modular or reusable code. Instead it's more like the method exists just to tidy up the implementation of its calling method. In essence, the method doesn't really stand on its own, so there's no point in treating it like an interface method. But as soon as a second method is making the same call it demonstrates that the code is in fact reusable and useful in more than just the original context, and able to stand on its own as a useful function. So at that point, it becomes a declared part of the private interface.
Some other coding style choices make answering this question really easy:
If you document every method at its declaration point, then not having a declaration means that either these methods are missing documentation, or they are documented at definition; either way it's inconsistent. If you follow the school of thought that most methods should be so self-explanatory from their name that they don't need documentation, this might not be an issue.
Some people advocate ordering methods from more general to more specific; in that model your example is ordered wrong, and the only way to fix it is to have a declaration.
There's also the question of whether you would find it annoying to get unexpected compiler errors when you do simple re-ordering or re-factoring just because you happened to start using a method earlier, and have to stop and add the declaration at that point.
I'm looking for a way to make an NSInvocation invoke a specific IMP. By default, it invokes the "lowest" IMP it can find (ie, the most-recently-overridden version), but I'm looking for a way to make it invoke an IMP from higher up in the inheritance chain. The IMP I want to invoke is determined dynamically, or else I'd be able to use the super keyword or something like that.
My thought was to use the -forwardInvocation: mechanism to capture a message (easy and already working) and then alter the IMP so it goes to a method that is neither the super implementation nor the furthest descendent's implementation. (hard)
The only thing I've found that comes remotely close is AspectObjectiveC, but that requires libffi, which makes it non-iOS compatible. Ideally I'd like this to be cross platform.
Any ideas?
disclaimer: i'm just experimenting
Trying out #bbum's idea of a trampoline function
So I think I've got things mostly set up; I've got the following trampoline that gets correctly added via class_addMethod(), and it does get entered:
id dd_trampolineFunction(id self, SEL _cmd, ...) {
IMP imp = [self retrieveTheProperIMP];
self = [self retrieveTheProperSelfObject];
asm(
"jmp %0\n"
:
: "r" (imp)
);
return nil; //to shut up the compiler
}
I've verified that both the proper self and the proper IMP are the right things prior to the JMP, and the _cmd parameter is also coming in properly. (in other words, I correctly added this method).
However, something is going on. I sometimes find myself jumping to a method (usually not the right one) with a nil self and _cmd. Other times I'll just crash in the middle of nowhere with an EXC_BAD_ACCESS. Ideas? (it's been a long time since I've done anything in assembly...) I'm testing this on x86_64.
NSInvocation is just an object representation of a message send. As such, it can't invoke a specific IMP any more than a normal message send could. In order to have an invocation call a specific IMP, you'd either need to write a custom NSInvocation class that goes through the IMP-calling routine or you'd have to write a trampoline that implements the behavior and then create an invocation that represents a message to the trampoline (i.e. you basically wouldn't be using NSInvocation for much of anything).
Added long after the fact, for reference:
You can do it with private API. Put this category somewhere convenient:
#interface NSInvocation (naughty)
-(void)invokeUsingIMP:(IMP)imp;
#end
and voila, it does exactly what you'd expect. I dug up this gem from one of Mike Ash's old blog posts.
Private API tricks like this are great for research or in-house code. Just remember to excise it from your appstore-bound builds.
Given that you already have the IMP, you simply need a way to do a very raw forward of the method call to said IMP. And given that you are willing to use an NSInvocation like solution, then you could also build a similar proxy class.
If I were faced with this, I would create a simple proxying class that contained the IMP to be called and the target object (you'll need to set the self parameter). Then, I would write a trampoline function in assembly that takes the first argument, assumes it is an instance of the proxying class, grabs the self, stuffs it into the register holding argument 0, grabs the IMP and *JMPs to it as a tail call.
With trampoline in hand, you would then add that trampoline as an IMP for any selector on the proxying class that you want forwarded to a particular IMP....
To achieve any kind of generic mechanism like this, the key is to avoid anything having to do with rewriting the stack frame. Avoid the C ABI. Avoid moving arguments about.
An untested idea:
Could you use object_setClass() to force the selection of the IMP that you want? That is…
- (void)forwardInvocation:(NSInvocation *)invocation {
id target = [invocation target];
Class targetClass = classWithTheImpIWant();
Class originalClass = objc_setClass(target, targetClass);
[invocation invoke];
objc_setClass(target, originalClass);
}
I think your best choice is to use libffi. Have you seen the port to iOS at https://github.com/landonf/libffi-ios? I haven't tried the port, but i have successfully invoked IMP with arbitrary arguments on the Mac.
Have a look at JSCocoa https://github.com/parmanoir/jscocoa it includes code to help you prepare a ffi_cif structure from a Method and it also contains a version of libffi that should compile on iOS. (Haven't tested either)
You should probably have a look at how we swizzle the implementation of a certain method on an instance of an object in https://github.com/tuenti/TMInstanceMethodSwizzler
Basically, you swizzle the method for all object of a class so when its called it look up in a dictionary whats is the implementation which has to be called for the target object, falling back to the original implementation if not found.
You can also use the private invokeWithImp: method, but this is discouraged if you intent to submit the app to the store.
you could add the IMP to the class using class_addMethod under a new selector and invoke that selector.
the temporary method can't be removed though.
What I am looking for is a way to programmatically verify a target object has been deallocated. Currently I have an NSLog statement in the dealloc methods of the objects I wish to observe.
The unit testing framework is from the Google Toolbox for the mac, and it working nicely. I am just not certain how to frame this particular test.
Use _GTMDevLog :
See the Advanced Stuff | Unit Test Logging on this page.
More info on DevLogNAssert.
You could swizzle the dealloc method. See MethodSwizzling on CocoaDev; a modern approach using Leopard's new method_exchangeImplementations function is (currently) near the bottom of the page.
Your implementation will need to tell your test case object that it had been called. One way to do this would be a static variable in the file where both the test case class and replacement dealloc method are defined; your test method sets that variable to NO, then releases the object, then asserts that the variable's value is now true.
In the past I've created a variable that counts the number of objects of a given class that have been allocated by incrementing the value in the constructor and decrementing it in the destructor. The unit tests just check that the variable is zero at the end of the test.
I did something very similar to this in C#/.Net. I used a "WeakReference" to keep track of the item, and tested that it no longer existed (see link). Can you translate this approach to your environment?
Link
Could you record the dealloc in some kind of event monitor service, so that the test code can then query with that to see if the dealloc has occured. Obviously you will record it by name or id, as the object is being dealloc'd...
I may be naive, but wouldn't a unit test of a deallocation consist of
allocating an object,
deallocating it through your method to be tested,
trying to call something from the object, and then
catching the exception and see if its type is correct?
I’ve written a function that releases the object and returns YES if the object got deallocated:
BOOL getsDeallocatedByReleasing(id object);
There’s also an advanced interface where you can run arbitrary code in a block and you will get a bool indicating if an object of given class was deallocated:
BOOL classGetsDeallocated(Class c, void (^block)(void));
The code uses method swizzling, it’s pretty ugly and definitely not thread-safe, but it works. You can find it on GitHub, I’ll keep it updated if I find any bugs.
P.S. After writing all that code (d’oh!), wouldn’t it be possible to add a single retain at the start, do whatever you want, tear down the object graph you are inspecting and check the object’s retain count?