Dynamic Functions - objective-c

Ok, well I have sorta of an odd situation. I have a two applications. One is the main application and the other is a helper bundle that is loaded during run time. What I want to do is to call a function defined within the main application from the bundle so that code does not have to be copied over. I have tried setting the header declaration for the function
NSString *TXReadableTime(NSTimeInterval date, BOOL longFormat);
within the helper bundle, but it still fails to compile. This is because one of my selectors is calling the function and the compiler is not finding it within the code. Only the header reference.
So I guess what my real question is, is there a way to have dynamic functions? One that is promised to the compiler, but is handled by a separate process. The helper bundle itself is allocated into memory so it has access to selectors of the main application, but I do not want to rewrite the function into a selector because it would require a lot of work.

Use -bundle_loader linker flag to specify the executable which will load the plugin. See ld man page, another Apple doc, and this informative blog post.

Related

Standard library containing dispatch_get_main_queue (GCD)

I'm trying to run some NSWindow functions from another thread on OSX. I am doing this via ctypes so need to find the library files.
dispatch_sync I found in libc.dylib but I can't find dispatch_get_main_queue, does anyone know the library that is in? Is it not in libc? I thought to use this based on here: Objective C Multi thread NSWindow alternative?
I also couldn't find the docs of the types used on opensource.apple can someone also help me find that for this Dispatch module.
dispatch_get_main_queue() is an inline function, so it doesn't end up in any library. It's compiled into every [Objective-]C/C++ file that uses it.
It compiles down to just (dispatch_queue_t)&_dispatch_main_q, more or less. That is, there's a global variable _dispatch_main_q and dispatch_get_main_queue() just returns its address, type cast to dispatch_queue_t.
On my 10.9.5 system, _dispatch_main_q is exported by /usr/lib/system/libdispatch.dylib.

Custom performance profiler for Objective C

I want to create a simple to use and lightweight performance profile framework for Objective C. My goal is to measure the bottlenecks of my application.
Just to mention that I am not a beginner and I am aware of Instruments/Time Profiler. This is not what I am looking for. Time Profiler is a great tool but is too developer oriented. I want a framework that can collect performance data from a QA or pre production users and even incorporate in a real production environment to gather the real data.
The main part of this framework is the ability to measure how much time was spent in Objective C message (I am going to profile only Objective C messages).
The easiest way is to start timer in the beginning of a message and stop it at the end. It is the simplest way but its disadvantage is that it is to tedious and error prone - if any message has more than 1 return path then it will require to add the "stop timer" code before each return.
I am thinking of using method swizzling (just to note that I am aware that Apple are not happy with method swizzling but these profiled builds will be used internally only - will not be uploaded on the App Store).
My idea is to mark each message I want to profile and to generate automatically code for the method swizzling method (maybe using macros). When started, the application will swizzle the original selector with the generated one. The generated one will just start a timer, will call the original method and then will stop the timer. So in general the swizzled method will be just a wrapper of the original one.
One of the problems of the above idea is that I cannot think of an easy way how to automatically generate the methods to use for swizzling.
So I greatly will appreciate if anyone has any ideas how to automate the whole process. The perfect scenario is just to write one line of code anywhere mentioning the class and the selector I want to profile and the rest to be generated automatically.
Also will be very thankful if you have any other idea (beside method swizzling) of how to measure the performance.
I came up with a solution that works for me pretty well. First just to clarify that I was unable to find out an easy (and performance fast) way to automatically generate the appropriate swizzled methods for arbitrary selectors (i.e. with arbitrary arguments and return value) using only the selector name. So I had to add the arguments types and the return value for each selector, not only the selector name. In reality it should be relatively easy to create a small tool that would be able to parse all source files and detect automatically what are the arguments types and the returned value of the selector which we want to profile (and prepare the swizzled methods) but right now I don't need such an automated solution.
So right now my solution includes the above ideas for method swizzling, some C++ code and macros to automate and minimize some coding.
First here is the simple C++ class that measures time
class PerfTimer
{
public:
PerfTimer(PerfProfiledDataCounter* perfProfiledDataCounter);
~PerfTimer();
private:
uint64_t _startTime;
PerfProfiledDataCounter* _perfProfiledDataCounter;
};
I am using C++ to use that the destructor will be executed when object has exited the current scope. The idea is to create PerfTimer in the beginning of each swizzled method and it will take care of measuring the elapsed time for this method
The PerfProfiledDataCounter is a simple struct that counts the number of execution and the whole elapsed time (so it may find out what is the average time spent).
Also I am creating for each class I'd like profile, a category named "__Performance_Profiler_Category" and to conforms to "__Performance_Profiler_Marker" protocol. For easier creating I am using some macros that automatically create such categories. Also I have a set of macros that take selector name, return type and arguments type and create selectors for each selector name.
For all of the above tasks, I've created a set of macros to help me. Also I have a single file with .mm extension to register all classes and all selectors I'd like to profile. On app start, I am using the runtime to retrieve all classes that conforms to "__Performance_Profiler_Marker" protocol (i.e. the registered ones) and search for selectors that are marked for profiling (these selectors starts with predefined prefix). Note that this .mm file is the only file that needs .mm extension and there is no need to change file extension for each class I want to profile.
Afterwards the code swizzles the original selectors with the profiled ones. In each profiled one, I just create PerfTimer and call the swizzled method.
In brief that is my idea which turned out to work pretty smoothly.

Can I use MSVCRT functions in my DLL Delay-Load Handler function?

I have already added delay loading to my project, using the instructions in
http://msdn.microsoft.com/en-us/library/151kt790.aspx
In the "delayhlp.cpp" (a sample implementation of the DLL load helper) __HrLoadAllImportsForDll, I saw that the writer avoids using any Standard C Library (MSVCRT) functions. Do I need to do the same in my handler function, which will be called by the sample DLL load helper?
I think the writer's reason is that someone might try to delay-load MSVCRT itself. I'm not going to do this. Will it then be safe for me to use MSVCRT functions?
Background Info. The reason for delay-loading the 3rd party DLL is because there is a function signature change between two versions, and I need to run my program using either version. I then provide a simple wrapper function to adapt the DLL's function signature to the one needed. This function is registered by the Delay-Load Handler (__pfnDliFailureHook2), when GetProcAddress fails.
Some testing. I added a breakpoint at the beginning of my handler function. I found that when the breakpoint is hit, the msvcrt.dll and msvcr90d.dll etc are already loaded (from Visual Studio's Modules pane). Does it mean that I can call CRT functions safely?
// Check to see if it is the DLL we want to load.
// Intentionally case sensitive to avoid complication of using the CRT
// for those that don't use the CRT...the user can replace this with
// a variant of a case insenstive comparison routine.
//
That's the more relevant comment, for those that don't use the CRT. You won't have a problem, the CRT is always loaded by the startup code.

LINUX: order of statically linked module loading

If I have two modules which are being statically linked in. One modules' module_init function depends on another module's module_init function having already run. Is there a way to force one module to load before the other?
Also, is the first module's init function guaranteed to finish before the second one is invoked?
Lastly, if the answer to the above is NO, what is the recommended way of synchronizing the two module init calls to make sure I don't run into issues?
Is there a way to force one module to load before the other?
Answer is surprisingly simple, make sure first module is first in Makefile:
obj-y += mod1.o
obj-y += mod2.o
is the first module's init function guaranteed to finish before the second one is invoked?
Yes, initcalls (module_init hook) in your case are called one-by-one. See init/main.c,
do_one_initcall() callers.
I'm assuming you want to fix the static initialization fiasco
Have a look at
http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html (init_priority)
How exactly does __attribute__((constructor)) work?
the -rdynamic linker flag for gcc/ld (this gives you some latitude to do compile time linking, and still use the runtime loader (dload))
Static Initialization Order Fiasco

How to find and remove unused class files from a project

My XCode project has grown somewhat, and I know that there are class files in there which are no longer being used. Is there an easy way to find all of these and remove them?
If the class files just sit in your project without being part of a target, just click on the project itself in the tree view, so you see all files in the table. Make sure you see the "Target" column in the table view, iterate through your targets and find the files that don't have a check anywhere -> they are no longer compiled.
But if you still compile the classes and they are no longer used, that case is a bit more difficult. Check out this project
http://www.karppinen.fi/analysistool/#dependency-graphs
You could create a dependency graph and try to find orphaned classes that way.
Edit: Link went dead, but there still seem to be projects of Objective-C dependency graphs around, for example https://github.com/nst/objc_dep
if they are C or C++ symbols, then you can just let the linker do the work for you.
if you're looking to remove objc symbols, then try to refactor the class name (e.g. to rename the class), and preview the dependencies that it turns up. if you reference classes/selectors/etc. by strings then... it may not be so effective. unfortunately, you often have to also test manually, to verify that removing a class does not break anything. remember that resources (like xibs) may reference/load objc classes as well.
This is a tricky question due to how dynamic objective-c is as you can never guarantee that a class is not going to be used.
Consider if you generate a class name and a selector at run time and then look up that class, instantiate that class and then call a method on that newly created object using that newly created selector. No where in your code do you explicitly name and instantiate that object but you are able to use it anyways. You could get that class name and selector name from anywhere outside of your code, even from some data from a server some where. How would you ever know which class is not going to be used? Because of this there are no tools that are able to perform what you are requesting.
Searching the project with the class name might be an option, thought it may not be the best solution. Specially it might be time consuming when you have many classes.