I'm working on porting PC OpenGL application onto Android. I've chosen to use that NDK android_native_app_glue framework stuff. As I understood, it would allow to me stay on C++ and write no even single JAVA code line. And it sounded promising.
The first unclear thing to me it data saving/loading. My application's data format is binary and my original PC-related code uses plain "stdio.h" FILE operations: fopen, fread, fwrite, etc to create, write and read from "mygame.bin" file. How do I port it onto Android?
Having googled it, I found that I must store and then use a "java environment" variable:
JNIEnv *g_jniEnv = 0;
void android_main(struct android_app* state) {
g_jniEnv = state->activity->env;
}
However, I still do not realize how to use this g_jniEnv to perform file operations.
Update:
Okay, I found that in Java, data saving can be performed as follows:
String string = "hello world!";
FileOutputStream fos = openFileOutput("mygame.bin", Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
So my questions is: given a pointer to JNIEnv, how do I rewrite this code fragment in C++?
You can still use stdio.h in an NDK project. #include and pound away.
The only trick is getting the path to your application's private data folder. It's available as state->activity->internalDataPath in android_main. Outside of that path, the app has no filesystem rights.
You will probably need your JNIEnv eventually one way or another. The entirety of Java API is not mirrored for the native subsystem; so hold on to that env. But native file I/O is right there.
Related
I'm an IOS developer and I know objective C. I wanna to create a stand alone mac app whose sole functionality is to patch another app available in same mac.
Lets say I have an app called X in my applications folder. This app X has some undesired behaviour. So I tried to modify this behaviour. I analysed the app's executable with the help of Hopper disassembler, I came to know that I have to change assembly instructions starting at 00000001003e3790. I changed those assembly instructions and produced the new executable. Then I replaced the old one with new executable and then that undesired behaviour now seems to be gone.
As most people would love to remove this undesired behaviour, I decided to write a patcher and distribute that patcher to them.
So how can I modify assembly instructions available inside the executable of app X in my patcher app then replace the original one with my modified version ?
It would be great if someone help me in right direction.
In general, you should ask the user for the location of the app bundle, in case it can`t be found in /Applications/.
You need to check whether the target executable inside that bundle has the same hash (it may be CRC, MD5, SHA — you name it) as the executable you had before patching it.
If the hashes match, then you are to open the file for writing and seek for the pre-hardcoded place where the wrong instructions are stored; you can determine that place by searching the patched file in a hex-editor for a long enough byte string beginning with your patched bytes.
And finally, you are to rewrite (a.k.a. patch) the target bytes with yours and close the file.
[UPD.] Example code for [3].
This does not require any ObjC-related mechanisms, and can be built and run using only the plain libc:
long PatchSomething(char *name, char *data, size_t offs, size_t size) {
long file = open(name, O_WRONLY);
if (file != -1) {
lseek(file, offs, SEEK_SET);
write(file, data, size);
close(file);
}
return file != -1;
}
where:
name is the name of the file to patch
data is the data to be written
offs is the file offset where the data shall be put
size is the data size; exactly size of the old bytes in the file would get rewritten
Is it possible to load .dll or static library(.a) file programmatially which returns assembly in objective-c for mac os x?
How assembly loading & unloading done in objective-c for mac osx?
I'll admit that even after reading Microsoft's documentation on the Assembly Class, it's still not clear to me what an Assembly is. They say:
Represents an assembly, which is a reusable, versionable, and self-describing building block of a common language runtime application.
The "reusable, versionable and self-describing" part sounds like a framework.
If indeed that's what you want to load, then you have a number of options. Your best best is to just link against the framework. The OS will automatically load it for you when your app starts up.
If you want to load it manually, there are a number of ways to do that. If it's a framework you're going to ship with your application, then you can simply put it into your app bundle's Frameworks folder, and then use:
NSBundle* frameworkBundle = [NSBundle bundleWithIdentifier:#"<your bundle's identifier>"];
if (frameworkBundle != NULL)
{
[frameworkBundle load];
}
You can also use dlopen() (see man dlopen(3) for details). This will load a dynamic library into your process space.
I have never had a reason to use dlopen() directly. I usually just link against the framework. On those rare occasions where my app may need to run on an older OS that doesn't support the framework, I have used the manual loading described above via NSBundle.
We're using static libraries in an iOS app.
Some of those static libraries require bundle resources.
I don't want to distribute those bundle resources as stand-alone files - I want them to be packaged with the static libraries they belong to.
So, I'm looking for a utility/script which can be integrated into the Xcode build process which gets pointed at a folder and automatically updates an auto-generated Objective-C class which allows me to retrieve the contents as a byte array (or whatever) of these resources - which will be built into the static library.
Does anyone already have this? I can't find anything. Obviously I can make it myself if I need to.
I don't know any ready to use utility that works with directories. But for single file it is trivial enough:
cat input_file | ( echo "unsigned char my_data[] = {"; xxd -i; echo "};" ) > output_file.c
It will produce file with my_data array containing your data. I think it would be easy to extend it to handle directories.
The (hypothetical for now) situation is the user of my system is going to be given a chunk of C code and needs my system to compile and run it in a chroot sandbox that is generated on the fly and I want to require the fewest files in the box as possible. I'm only willing to play with compiler and linker settings (e.g. static link everything I can expect to be able to find) and make some moderate restriction on what the code can expect use (e.g. they can't use arbitrary libs).
The question is how simple can I get the sandbox. Clearly I need the executable, but what about an ELF loader and a .so for the system calls? Can I dump either of them and is there something else I'll need?
You don't need anything except the executable to run a statically-linked hello world. You will, of course, need a lot more to compile it.
You can test this fairly easily, I did so with the following trivial C code:
#include <stdio.h>
int main() {
puts("Hello, world\n");
return 0;
}
compile it with gcc -static. Then make a new directory (I called it "chroot-dir"), move the output ("hello") into it. So the only file in the chroot is now the executable. Then run chroot chroot-dir ./hello, and you'll get Hello, world.
Note that there are some things that can not be compiled statically. For example, if your program does authentication (through PAM), PAM modules are always loaded dynamically. Also note that various files in /etc are needed for certain calls; any of the getpw* and getgr* functions, the domain name resolution functions, etc. will require nsswitch.conf (and some shared objects, and maybe more config files, and sometimes even more executables, depending on the lookup methods configured.) /etc/hosts, /etc/services, and /etc/protocols will probably be quite useful for any networking.
One easy way to figure out what files a program uses is to run it under strace. You must trust the program first, of course.
no need for any ELF loader. to check what dynamic libraries you need do ldd <executable>. If you manage to static compile everything, it won't need any .so. Beyond that, it's only about the data and directory structure your program might need.
But all this is only if you use the /usr/bin/chroot command; if you make your program call int chroot(const char *path); itself after making sure all dynamic libraries are loaded, they you won't need anything on the directory sandbox. not even the executable itself.
edit: A different idea: use TCC (or rather, libtcc to compile, link, load and run the given C chunk. run the whole process inside an 'outer' chroot jail, dropping to an 'inner' (empty) one just before execution. (of course, execute in a fork(), or you won't be able to break out of the 'inner' jail to the 'outer' one). You might also take advantage of libtcc's bound's checked execution.
I'm racking my brain trying to come up with an elegant solution to a DLL load problem. I have an application that statically links to other lib files which load DLLs. I'm not loading the DLLs directly. I'd like to have some DLLs in another folder other than the folder that the executable is in. Something like %working_folder%\dlls - I'd rather not have dozens (yes ... dozens) of DLLs in my %working_folder%.
I'm trying to develop something that is part of the main app that will adjust the search path # startup. The problem I'm running into is that this new custom DLL path isn't in the system search path. When I start the app it crashes (STATUS_DLL_NOT_FOUND) because the necessary DLLs are not in the appropriate places. What I'd like to do is to check # startup if this new custom DLL folder is in the process environment variable search path and if not add it. Problem is, the application attempts to load all these DLLs before the app executes one line of code.
How do I fix this? I've considered writing a help app that starts first, adjusts the environment variables appropriately and the launches the main app via CreateProcess. This will work I'm sure of it but it makes things difficult on the developers. When they debug the main app they're not going to launch a helper app first - not that they could even do that.
I've tried the registry app path feature with no success. Same chicken and egg problem as before.
What can I do here?
I found Matthew's answer worked for me.
In visual studio 2012 goto your project properties and in
Configuration Properties->Linker->Input->Delay Loaded Dlls
add each dll file that you want to not load until needed.
Although it no longer needs to run before main, this is my code to set the new search path
class RunBeforeMain
{
public:
RunBeforeMain()
{
const TCHAR* dllPathEnvName= name of env variable to directory containing dlls
const TCHAR* pathEnvName= TEXT("Path");
TCHAR newSearchPath[4096];
::GetEnvironmentVariable(dllPathEnvName, newSearchPath, MAX_PATH);
//append bin
_tcscat_s(newSearchPath, MAX_PATH, TEXT("bin;"));
size_t length = _tcslen(newSearchPath);
//append existing Path
::GetEnvironmentVariable(pathEnvName, newSearchPath + length, 4096-length);
::SetEnvironmentVariable(pathEnvName, newSearchPath);
}
};
static RunBeforeMain runBeforeMain; //constructor code will run before main.
[Edit - after re-reading the question I see that the problem you're having is that the DLLs are getting loaded before main starts]
I'm guessing that those libraries are written in C++ and are loading the DLLs from the constructor of some objects in global scope. This is problematic. Allow me to quote Yossi Kreinin:
Do it first thing in main(). If you use C++, you should do it first thing before main(), because people can use FP in constructors of global variables. This can be achieved by figuring out the compiler-specific translation unit initialization order, compiling your own C/C++ start-up library, overriding the entry point of a compiled start-up library using stuff like LD_PRELOAD, overwriting it in a statically linked program right there in the binary image, having a coding convention forcing to call FloatingPointSingleton::instance() before using FP, or shooting the people who like to do things before main(). It’s a trade-off.
[Original answer below]
See this page for the search algorithm used for loading DLLs. You can use SetDllDirectory() to add a directory to the DLL search path.
You also should be able to add a directory to the PATH environment variable using GetEnvironmentVariable() and SetEnvironmentVariable().
Another option is to change the current working directory to the folder containing the DLLs with SetCurrentDirectory(). Just make sure to change the working directory back after loading the DLLs if you ever load any files using relative filenames.
My recommendation is to use delayload linking for the DLLs and call SetDllDirectory() early enough so it can find them when the methods/functions are invoked.