Calling a function inside iOS static library from command line - ios

We have some functions made available to us in iOS static library. There is a header (.h) and the compiled (.a) file. Is there any way that the functions in the static library can be called from a command line ( either OS X, Windows or Linux )? I have researched this for couple of days now and I am starting to doubt if this is even possible? We don't deal with Apple/iOS/xcode environment and the vendor only has this static library. Any hints? If it is possible in anyway I am open to reading any and very documentation but at this time I am in doubt if this is even possible? thanks
While checking out what is possible, I ran this
lipo -info libExaNumberCalc.a
I ran the above and it says
Architectures in the fat file: libExaNumberCalc.a are : i386 armv7 x86_64 arm64
Wonder if the above adds any hope?

The first thing that springs to mind is that you could write thin wrapper around your library function and build/run it. Something like
// main.c
#include "your_library_header.h"
int main(int argc, char *argv[])
{
// parse & pass parameters if necessary from command line
your_lib_function();
return 0;
}
Build with something like
clang main.c -o output.file -lyourlibrary

Related

Getting the address of a section with Clang on OSX/iOS

For quite a while I've been using linker sections for registering elements that are used at runtime. I find that it's a simple way to make generic and extensible interface. A particularly useful use-case is something like unit tests or a multitool (e.g. busybox) so one can do something like:
$ ./tool <handler>
Where handler is a simple string that is "looked up" at runtime by walking the linker section. In this way, your parser doesn't have to "know" what commands are supported. It just finds their handlers in the linker section dedicated for them or it doesn't.
With GCC I've been doing something like (you can do this with Clang as well):
#define __tool __attribute__((__section__("tools")))
Then each handler I want to register gets a simple structure (with more or less information as needed)
struct tool {
const char *name;
const char *help;
int (*handler)(int argc, char **argv);
}
Then, for each tool you just do something like (often conveniently wrapped in a macro):
int example_tool0(int argc, char **argv)
{
return -1;
}
static const struct tool example_tool0 = {
.name = "exmaple_tool0",
.help = "usage: ...",
.handler = example_tool0
};
__tool static const struct tool *ptr = &example_tool0;
And used a such:
$ ./tool example_tool0
And because of __tool, each pointer registered in this way is packed into a linker section that can be walked.
Now, on GCC the linker creates two magic variables for each section: __start_SECTION and __stop_SECTION. So, to "walk" all of our registered handlers you just take the size of this section, divide by the size of a pointer, and then strncmp against the name (in this example) in the struct.
All of the above just to say, how can this be done using the OSX/iOS Clang-based toolchain? I would rather not use a custom linker script to achieve this seemingly simple operation.
Is there a way do this on OSX? I have worked around the issue by registering an empty entry at the beginning of the section and at the end. But doing so requires forcing the link order of the object files.
While OSX/iOS uses Clang as their platform compiler, they do not use the LLVM linker. Rather, they implement their own ld64 (which is open source) for whatever reason. So, it may just not be supported. I didn't readily see anything in man ld on OSX, but it's a bit info-dense.
For reference with ELF and GCC
And so this has been answered by others already. I did search, but I must have missed this answer. I've actually looked for an answer to this question many times before but must've never used the right words.
https://stackoverflow.com/a/22366882/2446071
In summary, apparently the linker supports syntax to define these desired symbols yourself:
extern char __start_SECTION __asm("section$start$SEGMENT$SECTION");
extern char __stop_SECTION __asm("section$end$SEGMENT$SECTION");

How to use iOS framework with Unity?

I'm trying to use an iOS native framework inside Unity, but I don't know how.
Inside my C# script, I call a native function like this :
[DllImport ("__Internal")]
private static extern void writeHello();
void Start () {
writeHello();
}
I have drag the iOS framework inside my project like this :
Link to my image
But when I deploy my app on iPad, xCode showing this error :
Undefined symbols for architecture armv7: "_writeHello", referenced
from:
RegisterMonoModules() in RegisterMonoModules.o ld: symbol(s) not found for architecture armv7 clang: error: linker command failed with
exit code 1 (use -v to see invocation)
I don't understand why, and I don't know if what I'm trying to do is possible.
Help! :)
Thanks,
Sennin
The iOS framework must be put in the xCode generated project, not in unity.
And the framework's functions must be wrapped in an extern "C" block (as shown here).
Then you will be able to use it in C# with dllimport.
The doc says that all files with extensions .a,.m,.mm,.c,.cpp located in the Assets/Plugins/iOS folder will be merged into the generated Xcode project automatically. The docs also says that subfolders are currently not supported, so, in your example, the "framework-helloUnity.framework" folder will be ignored.
It is important to note that .m files default to C-style bindings, while .mm files default to C++-style bindings. In other word, unless you use the extern "C" keyword, as Heilo suggested, your functions won't be found if you put them in .mm or .cpp files.
In other words, if you put the following:
void writeHello() {}
in a file named Assets/Plugins/iOS/myTestFile.m, your code should compile.
Found the solution thanks to this post : Calling Objective-C method from C++ method?
By doing like that :
void myWriteHello( void *test) {
[(id)test writeHello];
}
- (void) writeHello
{
NSLog(#"Hello World!");
}
and calling my C function from Unity
You have write the following function in your Xcode project any class
extern "C"
{
-(void) writeHello
{
}
}

how to link a static library for iOS

I have create a bunch of .o files (via gcc -c $file.c $someotherops -o $file.o). Now I want to link them into a static library.
I'm not exactly sure wether I am supposed to use ld or gcc for this. In the ld manual, it is said that I'm not supposed to use it directly. However, I cannot figure out the gcc parameters to create a static library.
I tried ld *.o -static -o libfoo.a but it complains about a lot of missing symbols (I think all from libc). I don't understand why it complains because it is supposed to be a static library. I thought it would check for the symbols once I link that static library to some other thing.
Another thing: I use /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/ld here (my target is iOS). It complains with the warning ld: warning: using ld_classic. What is this about?
Then I thought, maybe it needs to have the dynamic libraries specified. So I added -lc to link against libc. But it complains with can't locate file for: -lc. I added -L/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/usr/lib and there is a libc.dylib.
Any ideas?
About the -lc error: It got away after I specified -arch armv6. Then it complained about a wrong libcache.dylib (which must be linked from libc.dylib I guess because it didn't specified it). Adding -L.../usr/lib/system helped.
Now, for each single .o file, I get the warning ld: warning: CPU_SUBTYPE_ARM_ALL subtype is deprecated. What is this about?
And I still have a bunch of missing symbols, esp:
Undefined symbols for architecture armv6:
"start", referenced from:
-u command line option
(maybe you meant: _PyThread_start_new_thread)
"___udivsi3", referenced from:
_get_len_of_range in bltinmodule.o
_quorem in dtoa.o
_array_resize in arraymodule.o
_newarrayobject in arraymodule.o
_array_fromfile in arraymodule.o
_get_len_of_range in rangeobject.o
_inplace_divrem1 in longobject.o
...
"___unorddf2", referenced from:
_builtin_round in bltinmodule.o
...
I checked some of those symbols, e.g. ___udivsi3 in get_len_of_range. This function uses C arithmetic only, no external call. So this seems to be translated to use some external functions like ___udivsi3. But what libraries is this in?
-lgcc_s.1 fixed most of the ___udivsi3 and related missing symbols. The start symbol is still missing. What does -u command line option mean?
From here, I got the feeling that maybe ld isn't the right tool after all. There, a simple call to aris used. And this seem to make more sense. I will check if that does work and transform this into an answer then.
While playing more around, ar throw some warnings at me when building a fat static library. It gave me the hint to use libtool instead. That is what I'm doing now, i.e. libtool -static -o libfoo.a *.o. Also I switched the compiler to /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clangbut not sure if that matters.
Now, at compiling some test application which links to this static library, I get these warnings:
ld: warning: PIE disabled. Absolute addressing (perhaps -mdynamic-no-pic) not allowed in code signed PIE, but used in __PyBuiltin_Init from /Users/az/Programmierung/python-embedded/libpython.a(bltinmodule.o). To fix this warning, don't compile with -mdynamic-no-pic or link with -Wl,-no_pie
ld: warning: 32-bit absolute address out of range (0x1001B70C4 max is 4GB): from _usedpools + 0x00000004 (0x001B70CC) to 0x1001B70C4
ld: warning: 32-bit absolute address out of range (0x1001B70C4 max is 4GB): from _usedpools + 0x00000000 (0x001B70CC) to 0x1001B70C4
What are they about? I don't use -mdynamic-no-pic. I also don't really see in _PyBuiltin_Init how I use absolute addressing there.
Also, what are these absolute addresses out of range about? Edit: These were some really huge allocations. I just removed this code for now (this was WITH_PYMALLOC, if anyone is interested in these specific Python internals).
When I start it on my iPhone, I get the abort:
dyld: vm_protect(0x00001000, 0x00173000, false, 0x07) failed, result=2 for segment __TEXT in /var/mobile/Applications/C15D9525-E7DC-4463-B05B-D39C9CA24319/...
When I use -no_pie for linking, it doesn't even link. It fails with:
Illegal text-relocation to ___stderrp in /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk/usr/lib/libSystem.dylib from _read_object in /Users/az/Programmierung/python-embedded/libpython.a(marshal.o) for architecture armv7
I solved the PIE disabled, Absolute addressing error. I had a -static in my command line Clang. Once I removed that, the warning got away, as well as the dyld/vm_protect error. It was the first time it actually run some code.
Until I hit another strange error about integer comparison. Whereby this looks more like a bug in their Clang build.
It all works now. Basically, the answer is:
Just compile every *.c file as usual to *.o files. The only real difference is the different GCC/Clang, the -arch armv7, the different SDK / include dirs.
Use libtool -static -o libfoo.a *.o to build the static library.
That's it. The other problems in my question were just wrongly headed tries.
If anyone gets here by searching for the dyld: vm_protect(...) runtime error but you are using XCode, the -static flag mentioned in the OP is likely the issue.
Get rid of it by switching "Enable linking with shared libraries" to "Yes" (the default) in the LLVM compiler language settings. (This removes GCC_LINK_WITH_DYNAMIC_LIBRARIES = NO from the project file).

dyld API on iPhone - strange output

I have three question for you, all related to dyld :)
I have been using this dyld man page as a basis. I have compiled the following code and successfully executed the binary on my jailbroken device.
#include <stdio.h>
#include <mach-o/dyld.h>
int main(int argc, const char* argv[]) {
uint32_t image_count, i;
image_count = _dyld_image_count();
for (i = 0; i < image_count; i++) {
printf("%s\n", _dyld_get_image_name(i));
}
return 0;
}
I thought that these functions let me find all the shared libraries that are loaded in my program's address-space. On my mac, the output is pretty straightforward: It shows the paths to all the libraries that are currently loaded in memory. On my iPhone the output is nearly the same - i also get filepaths - but there are no files at the specified location. (On my mac on the other hand, i can locate the files!)
This is a sample line from the output:
/usr/lib/system/libdyld.dylib
According to ls, iFile and all the other tools i've used, this directory (/usr/lib/system/) is empty. Why? Where are those files?
Another thing i'd like to know is: Is it possible to locate a library in memory? From what offset to what offset the library is mapped into memory? I think i know how to find the beginning but i have no idea how to find the end of the library. To find the beginning, i'd use the address returned by _dyld_get_image_header - Is that correct?
Last question: I wanted to load a dynamic lib system-wide so i assumed i could use DYLD_INSERT_LIBRARIES to do just that. However, every binary i try to execute after inserting my lib crashes and produces a bus error! Did i forget something or is it the dynamic library that causes the crash?
the libraries are located at :
/System/Library/Caches/com.apple.dyld/dyld_shared_cache_armv6 (_armv7)
This is a big file were all the single libraries have been joined into one large one.
See http://iphonedevwiki.net/index.php/MobileSubstrate for hooking on jailbroken device
Yes one can determine the position of a dylib in memory, even on non jailbroken devices.
parse the LC_SEGMENT(_TEXT)-Section Header(_text) of the library then you can get the base address of the library and the size of the TEXT __text segment. Then query for the vmslide. Add this to the base address of the TEXT __text.
A detailed description of the mach-o file format can be found here:
https://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/MachORuntime/Reference/reference.html. Pay special attention to "segment_command"-structure.

Code coverage with Xcode 4.2 - Missing files

I followed Claus's post to set up code coverage on Xcode 4.2 with LLVM 3.0. I'm able to see test coverage files, but they're only for my unit test classes, not my actual project classes. I've tried setting Generate Test Coverage Files and Instrument Program Flow to Yes on my main target, but that didn't help, as it failed with the following error:
fopen$UNIX2003 called from function llvm_gcda_start_file
To clarify, I don't think that's even the right approach - I just tried it to see if it would generate code coverage on my project classes.
At this point, I'd be happy to try anything that gets code coverage working on my app. Any suggestions?
You are expecting linker problem, profile_rt library uses fopen$UNIX2003 and fwrite$UNIX2003 functions instead of fopen and fwrite.
All you need is to add the following .c file to your project:
#include <stdio.h>
FILE *fopen$UNIX2003( const char *filename, const char *mode )
{
return fopen(filename, mode);
}
size_t fwrite$UNIX2003( const void *a, size_t b, size_t c, FILE *d )
{
return fwrite(a, b, c, d);
}
This code just remaps the missing functions to standard ones.
Note on $UNIX2003 suffix:
I've found an Apple document saying:
The UNIX™ conformance variants use the $UNIX2003 suffix.
Important: The work for UNIX™ conformance started in Mac OS 10.4, but was not completed until 10.5. Thus, in the 10.4 versions of libSystem.dylib, many of the conforming variant symbols (with the $UNIX2003 suffix) exist. The list is not complete, and the conforming behavior of the variant symbols may not be complete, so they should be avoided.
Because the 64-bit environment has no legacy to maintain, it was created to be UNIX™ conforming from the start, without the use of the $UNIX2003 suffix. So, for example, _fputs$UNIX2003 in 32-bit and _fputs in 64-bit will have the same conforming behavior.
So I expect libprofile_rt to be linked against 10.4 SDK.
I use CoverStory http://code.google.com/p/coverstory/ a GUI for .gcda and .gcno files.
The documentation explains the settings needed to generate these files http://code.google.com/p/coverstory/wiki/UsingCoverstory.

Resources