Objective-C ParseKit return value - objective-c

In flex/lex/bison/yacc (all of which I just started reading about), you can set "$$" to be equal to some value ($1,$2,$3) and that's the value that gets returned. At least I think that's how it works.
In ParseKit, you are given a stack so I imagine that the ($1,$2,$3) would be the first three values on the stack for example. But then I think what you would want to do is pop those values off the stack and put your return value on the stack. I see that the stack comes with a push method. Do you have to pop the incoming values first before pushing something on?
Thanks

Developer of ParseKit here. I would say: it depends. A few thoughts:
Yes, it is often useful/desirable to store objects/values on the assembly's stack by calling -[PKAssembly push:] on the assembly sent to your parser delegate callbacks. Later callbacks will find these values on the assembly's stack and may want to take action when they are found.
Another option: if your callback methods are building some result object, you usually want to store it as the -[PKAssembly target] property of the assembly passed into your callback method. So you have two places where you can store values: the assembly's target or the assembly's stack. The target is the 'correct' place for this, but often the stack is also convenient. Either is fine, but i would say: store temp values on the stack, but store the ultimate object you are building as the target. But again, you can do either.
Yes, your callbacks should often want to pop values off the stack first, but that is not required. Think of if this way: Your delegate callback method receives a PKAssembly object as a parameter. And usually your callback method will inspect the assembly's stack and take action depending on what it finds there. Usually, in your callback, you'll want to pop the values you find there, if you are taking action on them. Basically: your callback should pop the values it is interested in/taking action on, because in some sense your callback was the intended recipient of those items/information.

Related

How does the JVM know how many values to pop into a new frame when invoking a method via invokevirtual?

When a method is called via invokevirtual, the calling method pops off the values to pass to the called method along with the objectref and places them in the new stack frame.
How does it know which stack entry is the objectref? My guess is that it does so by looking at the type of the called method and parses this to determine how many values to pop off, but this seems extremely inefficient. Is there some other mechanism that I'm overlooking?
When you use the class file format as starting point, the method descriptor is the only way to determine, which values from the operand stack have to become the first local variables of the new stack frame.
As an exception to the rule, the invokeinterface instruction has an embedded count which can be used to determine the number of (type 1) elements to consume. As the documentation states:
The count operand of the invokeinterface instruction records a measure of the number of argument values, where an argument value of type long or type double contributes two units to the count value and an argument of any other type contributes one unit. This information can also be derived from the descriptor of the selected method. The redundancy is historical.
This historical redundancy doesn’t change the fact that the JVM has to cope with method descriptors as the source of this information, e.g. for invokevirtual, invokestatic, invokespecial, or invokedynamic. Further, a conforming JVM is required to verify this information, to throw an error if the invokeinterface’s count differs from the count derived from the method descriptor.
Generally, the verifier is responsible for detecting when method invocations are inconsistent to the stack frame’s state and therefore, has to process the method descriptors and model their effect on the operand stack. This implies that, unless you’re using a JVM that verifies each instruction right before its actual execution, it has to handle these descriptors even without executing an actual invocation. The obvious solution is to convert the method descriptors into an easier-to-process internal representation in a first step.
In short, these method descriptors are inefficient but with a reasonable JVM implementation you’re paying the costs only once, not for every invocation.
There's no one "right" way to do this, but the simplest strategy is to leave the values on the stack, and the called method refers to them via negative offsets. For example, if the called method has 3 params, they're referenced from the base stack offset minus 3, 2, and 1. Each is copied to a local variable and then referenced in the usual manner. The stack offset can be updated to reflect that the params have been consumed. Of course, each local param can also be initially assigned by a bunch of pops, one for each param.
Other tricks can be performed to speed things up. There's no reason that local variables need to be stored differently than the stack. They can be stored on the stack itself. The passed in params occupy their original locations on the stack, and then additional space is allocated for the remaining local variables by just updating the stack offset. A base stack offset is remembered, and all local variables are referenced via the base offset.
Essentially, a local variable is just like a stack slot, except it can be accessed at any time, regardless of what's currently been pushed on top.

Thread safe hooking of DirectX Device

I successfully hooked BeginScene/EndScene methods of DirectX9's DeviceEx, in order to override regions on the screen of a graphics application. I did it by overriding the first 'line' of the function pointed by the appropriate vtable entry (42 for EndScene) with an x86 jump command.
The problem is that when I would like to call the original EndScene method, I have to write the original code overriden by the jump. This operation is not thread safe, and the application has two devices used by two threads.
I tried overriding the vtable entry or copying it and override the COM interface pointer to the vtable, neither ways worked. I guess the original function pointer is cached somewhere or was optimized in the compilation.
I thought about copying the whole original method body to another memory block, but two problems I'm afraid of: (1) (the easy one I think) I don't know how to discover the length of the method and (2) I don't know if the function body stores offsets which are relative to the location where the function is in memory.
I'm trying to hook WPF's device, if it can help somehow.
Do anyone know a thread safe way for such hooking?
Answering my own question: It seems that for my purpose (performing another method before or instead of the original one within my own process), 'trampoline' is the answer. Generally it means I need to make another code segment that makes exactly what the overriden assembly commands did.
Because it is not an easy task, using an external library is recommended.
A discussion about this topic:
How to create a trampoline function for hook

What happens when a method is called? Where are the arguments pushed?

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.

In a singleton class (in my case C++), if one method is called more than once, will the locals be on the stack?

i have singleton class , when calling one of the singleton methods more then once in the same time , and this method has local variables . does each method call of the singleton gets its own private stack , do i need to worry about sharing/mixing local variable data between calls ?
Using local variables in a class method (not important whether it is a singleton) is no different from using local variables in a regular function. The local variables will not get mixed up.
No, you do not need to worry about that. To correct your terminology: "does each method call of the singleton gets its own private stack" -- not its own stack but each method call gets its own stack frame so you are alright.
A singleton method is just the same as an ordinary function (in C++). Think of local variables in the same way.
Note that this does not apply to static local variables, which are specifically shared between method calls.
Each method will gets its own private stack. The only possibility to take care about sharing are static variables inside the class.... but as ur class is singleton that applies to the instance variables of ur class too. Local variables of the method would always be freash in the stack no need to take care about them.
I'm not sure if you're talking about recursion or multiple thread calls, so I'll assume you mean recursion.
Each time you call the method any local variables that are not declared static are allocated on the stack. The way this works is that each call has it's own stack "frame" When the call is finished, the stack frame is released (and all local variables are destroyed).
So when function foo() is called it's local variables are in a frame on the stack, let's call it frame A. If foo calls itself, another frame is added, let's call it B. During the life of this second call, both frames A and B exist, but A is essentially dormant (usually, the data in A can be modified indirectly, e.g. via pointers). When the second call exits the B frame is released and the A frame becomes active again. Finally, when the top call is finished, the A frame goes away.
Since there is a limited amount of stack space, you have to be careful not to create more frames than the stack can hold. If you do, the stack is said to "overflow".

How exactly is NSPrintInfo's sharedPrintInfo shared?

Apple's documentation for NSPrintInfo states in part:
A shared NSPrintInfo object is automatically created for an application and is used by default for all printing jobs for that application.
The method sharedPrintInfo returns the shared NSPrintInfo. What's not explicitly stated is if you alter that object (e.g., by using setOrientation), do said alterations "stick" with the shared object? I.e., is the object you get back a singleton or a fresh copy of the shared object?
One reason I ask is because I've seen in some of Apple's sample code where they explicitly call setSharedPrintInfo at the end of a print job. Why do they do that if the shared object is a singleton?
Update
It seems I have to be clearer in my question. From Apple's documentation, there exists an instance of NSPrintInfo that is the "shared" one. This "shared" instance is used by default when no NSPrintInfo object is used explicitly in method calls. The method sharedPrintInfo returns a pointer to this "shared" instance.
What's not clear is whether sharedPrintInfo clones the "shared" instance and returns a pointer to that, or simply returns a pointer to the existing instance.
If cloned, then any call such as one to setOrientation will affect the clone only. If I wanted to alter the orientation of the "shared" instance also, I would have to call setSharedPrintInfo supplying the altered clone as an argument.
If not cloned, then it's not clear why Apple's sample code explicitly calls setSharedPrintInfo because all method calls altering the state of the NSPrintInfoObject returned by sharedPrintInfo already affected the "shared" instance.
What's not explicitly stated is if you alter that object (e.g., by using setOrientation), do said alterations "stick" with the shared object? I.e., is the object you get back a singleton or a fresh copy of the shared object?
Setters ordinarily return void; they don't return the object whose property you set. NSPrintInfo's setOrientation: method is one example.
Methods that return a copy of the receiver with the change applied say so explicitly in their name—for example, stringByAppendingString: (returns a modified copy), as opposed to appendString: (modifies the receiver).
So NSPrintInfo's setters only affect the object you send those messages to. If you send setOrientation: to the shared print info, you modify that object; you aren't creating a new print info.
OK, now for your actual question.
If you look at NSDocument, you'll see that each document can have its own print info. When the user enters Page Setup, they do so in a sheet on the document window, and their changes only affect that document—which is only possible by giving each document its own print info. If your app isn't document-based, it's probably a single-window app, and one print info for the whole process will do just fine.
The documentation for NSDocument calls out one specific case: You can override its printInfo method in your NSDocument subclass to always use the shared print info object. I can't imagine why you would do that, but in that case, the shared print info object is literally shared between all your open documents.
What's not clear is whether sharedPrintInfo clones the "shared" instance and returns a pointer to that, or simply returns a pointer to the existing instance.
In Cocoa, a sharedFoo method returns the shared foo object. It doesn't make a copy of it—that would defeat its purpose, which is to access the shared object.
This rule is also true of defaultFoo methods (e.g., [NSFileManager defaultManager]). Don't ask me why they call some of these methods defaultFoo and others sharedFoo. ☺
If you ever do want your own copy, many classes will let you make one; NSPrintInfo is one example that explicitly does allow this. Other classes (the shared panels in particular, such as NSColorPanel) exist in one and only one instance.
I don't know the answer to your question, but here's a simple test to find out: call sharedPrintInfo twice and compare the pointers. If they're the same, then no, you get the same NSPrintInfo object back each time. If they're different, then you get a different object back each time. You could do this in the debugger and have your answer in sixty seconds.
The NSPrintInfo documentation states the following, which seems pretty clear:
A shared NSPrintInfo object is automatically created for an application
and is used by default for all printing jobs for that application.
You can also initialize an instance of this class using the initWithDictionary: method.
You can use this dictionary to store custom information associated with a print job.
This would indicate that you can either use the shared object OR create your own.
Now to the second part of your question, why do the Apple examples call setSharedPrintInfo: ?
If you create your own using initWithDictionary: you CAN then store it to be the new shared one. But you don't have to.
source: Mac Dev Center, NSPrintInfo Class Reference
It's not a singleton. There's a shared NSPrintInfo object, because most apps only need one. You can also create additional NSPrintInfo instances if that's appropriate to your situation.